美文网首页转载的文章
ios 自定义Button实现 按钮标题在图标下方

ios 自定义Button实现 按钮标题在图标下方

作者: GrayMantis | 来源:发表于2017-07-20 14:23 被阅读2次

import UIKit
//  自定义button
class myButton: UIButton {
    
    
//  重写isHighlighted (重写目的: 在改变btn的transform时 不让去其调用layoutSubviews)
//因为这时一旦调用layoutSubviews , btn的位置也会跟着变化
    override var isHighlighted: Bool {
        get {
            return false
        } set {
            //  空实现
        }
    }
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        // 设置图片的模式 -> 原始大小居中显示
        imageView?.contentMode = .center
        //  设置文字居中
        titleLabel?.textAlignment = .center

//--------------下面这些也可以在外部设置---------------

        //  设置文字颜色
        self.setTitleColor(UIColor.darkGray, for: .normal)
        //  设置文字字体大小
        titleLabel?.font = UIFont.systemFont(ofSize: 14)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //  ----------调整系统子控件的位置-------重要--------
    override func layoutSubviews() {
        super.layoutSubviews()
        //  设置图片的大小
        //  执行transform动画,不能使用frame(注意)
        imageView?.width = width
        imageView?.height = width
        //  图片的y轴
        imageView?.y = 0
        //  设置文字label的大小
        titleLabel?.width = width
        titleLabel?.height = height - width
        //  设置title的y坐标
        titleLabel?.y = width
        titleLabel?.x = 0

    }

}
 

相关文章

网友评论

    本文标题:ios 自定义Button实现 按钮标题在图标下方

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