iOS 自定义控件在Xib中属性显示和效果实时渲染

一、简介

在iOS中,UIButton只能显示一个图片在左,文字在右的按钮,如下图:


普通按钮

但有时候,我们需要一个图片在上方,文字在下方的按钮,并且能在Storyboard或者Xib中显示自定义按钮,如下图:


自定义实时渲染按钮

二、实现

直接上代码:

import UIKit

@IBDesignable // 给该类加上@IBDesignable关键字,则可在xib中渲染
class CustomButton: UIButton {
    
    // @IBInspectable:给xib提供设置属性,可以xib中看到此属性
    @IBInspectable var borderColor:UIColor?{
        didSet{
            self.layer.borderColor = borderColor?.cgColor
        }
    }
    
    // @IBInspectable:给xib提供设置属性,可以xib中看到此属性
    @IBInspectable var borderWidth:CGFloat = 0{
        didSet{
            self.layer.borderWidth = borderWidth
        }
    }
    
    // @IBInspectable:给xib提供设置属性,可以xib中看到此属性
    @IBInspectable var cornerRadius:CGFloat = 0{
        didSet{
            self.layer.cornerRadius = cornerRadius
            self.layer.masksToBounds = true
        }
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        guard let titleLabel = titleLabel, let imageView = imageView else { return }
        
        imageView.frame.origin.y = 10
        imageView.center.x = frame.width * 0.5
        
        titleLabel.sizeToFit()
        titleLabel.center.x = frame.width * 0.5
        titleLabel.frame.origin.y = imageView.frame.maxY + 5
    }
}

最后,别忘记更改Custom Class自定义类,如图:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容