美文网首页
UIButton调整内部的子控件的位置

UIButton调整内部的子控件的位置

作者: eryuxinling | 来源:发表于2016-07-30 09:55 被阅读64次

    1.此方法不可以更改

    // 注意:在按钮外面改的尺寸,按钮的内部都会覆盖掉
    button.titleLabel.frame = CGRectMake(0, 0, 100, 70);
    button.imageView.frame = CGRectMake(100, 0, 70, 70);
    

    2.可以通过自定义UIButton,重写布局方法更改

    - (instancetype)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            // 文本居中
            self.titleLabel.textAlignment = NSTextAlignmentCenter;
            // 改变图片的内容模式
            self.imageView.contentMode = UIViewContentModeCenter;
        }
        return self;
    }
    /**
     *  重写两个方法
     */
    - (CGRect)titleRectForContentRect:(CGRect)contentRect {
        return CGRectMake(0, 0, 100, 70);
    }
    
    - (CGRect)imageRectForContentRect:(CGRect)contentRect {
        return CGRectMake(100, 0, 70, 70);
    }
    
    #pragma mark - 方式二
    - (void)layoutSubviews {
        [super layoutSubviews];
        // 设置子控件的位置
        self.titleLabel.frame = CGRectMake(0, 0, 100, 70);
        self.imageView.frame = CGRectMake(100, 0, 70, 70);
    }
    
    // 设置按钮的内边距
    // 1.设置内容(包括图片和文字)
    self.button.contentEdgeInsets = UIEdgeInsetsMake(-20, 0, 0, 0);
    
    // 2.设置图片
    self.button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10);
    
    // 3.设置标题
    self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
    

    相关文章

      网友评论

          本文标题:UIButton调整内部的子控件的位置

          本文链接:https://www.haomeiwen.com/subject/wattsttx.html