关于UIButton如何调整内部子控件

来源:互联网 发布:二手车交易平台源码 编辑:程序博客网 时间:2024/05/02 01:43

layoutSubviews在以下情况下会被调用:

1、init初始化不会触发layoutSubviews2、addSubview会触发layoutSubviews3、设置view的Frame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化4、滚动一个UIScrollView会触发layoutSubviews5、旋转Screen会触发父UIView上的layoutSubviews事件6、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件
自定义按钮的实现文件,继承于UIButton#import "WkButton.h"@implementation WkButton-(instancetype)initWithFrame:(CGRect)frame//只要通过代码方式创建对象,就会调用initwithframe方法{    if (self = [super initWithFrame:frame])    {        self.titleLabel.textAlignment = NSTextAlignmentCenter;        self.imageView.contentMode = UIViewContentModeScaleAspectFill;    }    return self;}#pragma make - 方式一:重写两个方法//重写2个方法//    -(CGRect)titleRectForContentRect:(CGRect)contentRect//    {//        return CGRectMake(0, 0, 100, 70);//    }//    -(CGRect)imageRectForContentRect:(CGRect)contentRect//    {//        return CGRectMake(100, 0, 70, 70);//    }#pragma mark - 方式二:layoutSubviews-(void)layoutSubviews{    [super layoutSubviews];    //设置子控件的位置    self.titleLabel.frame = CGRectMake(0, 0, 100, 70);    self.imageView.frame = CGRectMake(100, 0, 70, 70);}@end////  ViewController.m//  Wk-day1////  Created by Mac on 16/8/22.//  Copyright © 2016年 Mac. All rights reserved.//#import "ViewController.h"#import "WkButton.h"@interface ViewController ()@end控制器的实现文件@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    UIButton *button = [WkButton buttonWithType:UIButtonTypeCustom];    button.frame = CGRectMake(100, 100, 170, 70);//此处触发layoutSubviews    button.backgroundColor = [UIColor purpleColor];    [button setTitle:@"普通按钮" forState:UIControlStateNormal];    [button setImage:[UIImage imageNamed:@"miniplayer_btn_playlist_normal"] forState:UIControlStateNormal];    button.imageView.backgroundColor = [UIColor yellowColor];    button.titleLabel.backgroundColor = [UIColor blueColor];    [self.view addSubview:button];}@end

Demo

0 0