标签:
1.
在使用layoutSubviews方法调整自定义view内部的子控件坐标时,最好不要使用子控件的centerX,centerY属性,否则会出现奇怪的bug。
如果一定要用,务必仔细检查,该子控件的width,height是否已经赋值。
eg1. 在self.imageView.width尚未赋值时,使用self.imageView.centerX
/**自定义控件调整内部子控件frame需在该方法中,一旦外面修改自定义控件的宽高frame,或者每次点击按钮,都会立刻调用该方法进行重新布局*/ - (void)layoutSubviews { //必须调父类 [super layoutSubviews]; //self为自定义的Button(80*80),imageView和titleLabel是其内部子控件 self.imageView.y = self.height * 0.1; self.imageView.centerX = self.width * 0.5; //因为此时还未给self.imageView.width赋值,其宽度为0。这会导致centerX和x的值一样,显示在父控件一半的位置。(即self.imageView.x = 40;) self.imageView.height = self.height * 0.5; self.imageView.width = self.imageView.height; //此处设置imageView.width为40,这样imageView的frame为(40,10,40,40),此时centerX为60. //页面加载好了,第一次点击buttion时,会调用layoutSubView方法重新布局,此时imageView已经有宽度,x和centerX各算各的,发现centerX本应该在40的位置,现在却在60位置,于是整个imageView向左移动20点。
eg2. 在self..width尚未赋值时,使用self..centerX
self.indicatorView.width = button.titleLabel.width; ////此句必须放在centerX上面,否则width未赋值(等于0),centerX和x是一样的 self.indicatorView.centerX = button.centerX; //一定要等于button的中心点,不能等于titleLabel中心点,因为titleLabel坐标是相对于button来算的
2.
[self.tabBar layoutIfNeeded]; //立刻重新布局,强制刷新,强制布局
[self.view setNeedsDisplay]; //下次刷新屏幕时(很快,大概1/60秒),重新绘制self.view
- (void)layoutSubviews { } //该方法不应被手动调用,一般用于重写。它可以用来调整自定义控件内部的子控件frame,一旦外面修改自定义控件的frame/宽高,或者每点击一次按钮,系统会让自定义控件立刻调用该方法进行重新布局*/
3.
自定义UIView时,使用autolayout时,注意都有一个setTranslatesAutoresizingMaskIntoConstraints:BOOL
//UIView.h 任意一个UI控件都有如下属性 @property(nonatomic) BOOL translatesAutoresizingMaskIntoConstraints Description描述: A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints. If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to NO, and then provide a nonambiguous, nonconflicting set of constraints for the view. By default, the property is set to YES for any view you programmatically create(代码创建). If you add views in Interface Builder, the system automatically sets this property to NO.
UIView都有一个autoresizesSubviews属性,决定是否自动调整子控件。默认是YES。该属性等价于storyborad或xib中的Autoresizes Subviews,具体见下图:
//UIView.h @property(nonatomic) BOOL autoresizesSubviews Description用途: When set to YES, the receiver adjusts the size of its subviews when its bounds change. The default value is YES.
4.谨记:按钮的文字/文字颜色/图片都是分状态的,直接设置是错误的。
//alloc,init出来的system按钮默认黑色,如果改为custom,默认是白色,必须设置颜色
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//self.titleLabel.textColor = [UIColor blackColor]; //按钮的文字/文字颜色/图片都是分状态的,直接设置是不对的。
[button setTitle:square.name forState:UIControlStateNormal]; //正确
//button.titleLabel.text = modal.text; //错误
button.titleLabel.font = [UIFont systemFontOfSize:16]; //只有字体设置是无需分状态
标签:
原文地址:http://www.cnblogs.com/stevenwuzheng/p/5587030.html