UIButton默认的文字和图片的frame是不能修改的,即使是重新设置frame也没有用,以前只知道通过layoutSubViews这个方法来修改,今天偶然发现了另外一种修改方法,特此记录。
//
// IButton.m
// IButton
//
// Created by Jerry.Yao on 16/11/20.
// Copyright © 2016年 Jerry.Yao. All rights reserved.
//
#import "IButton.h"
@implementation IButton
// 方法一:修改title和image的frame
- (void)layoutSubviews
{
// 必须调用父类的方法
[super layoutSubviews];
self.titleLabel.frame = CGRectMake(0, 0, 50, 20);
self.imageView.frame = CGRectMake(50, 0, 100, 100);
}
// 方法二::重写UIButton修改子控件frame的方法
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
return CGRectMake(0, 0, 50, 20);
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
return CGRectMake(50, 0, 100, 100);
}
@end
本文介绍两种自定义UIButton中文字和图片布局的方法。一种是通过重写layoutSubviews方法直接调整位置,另一种则是重写titleRectForContentRect和imageRectForContentRect方法实现布局定制。
1万+

被折叠的 条评论
为什么被折叠?



