美文网首页
Swift自定义按钮

Swift自定义按钮

作者: 轻描淡写swift | 来源:发表于2017-12-25 15:20 被阅读30次
Snip20171225_5.png

通常我们设置的按钮是图片在右边,文字在左。所以我们需要自定义按钮来实现我们一些需求. 主要就是控制一下layoutSubviews里面计算一下尺寸
1.继承UIButton. 然后重写这几个方法,
2.接着使用改类创建就对象就好
3.可以在init 中设置一些自己固定的属性

class CustomBtn: UIButton {

    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        titleLabel?.font = UIFont.systemFont(ofSize: 12)
        setTitleColor(UIColor.green, for: UIControlState.normal)
        setImage(UIImage(named:"navigationbar_friendattention"), for: UIControlState.normal)
        setImage(UIImage(named:"navigationbar_friendattention_highlighted"), for: UIControlState.highlighted)
        sizeToFit()

    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        
        titleLabel?.frame.origin.x = 20
        
        imageView?.frame.origin.x = 20 + titleLabel!.frame.size.width
    }

}

扩展
Snip20171225_14.png

代码留给你,喜欢和点赞留给我https://gitee.com/lanyingwei/codes/ebx5hj6q3d1vsop7zrmlt98

相关文章

网友评论

      本文标题:Swift自定义按钮

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