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

一、简介

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


iOS 自定义控件在Xib中属性显示和效果实时渲染_第1张图片
普通按钮

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


iOS 自定义控件在Xib中属性显示和效果实时渲染_第2张图片
自定义实时渲染按钮

二、实现

直接上代码:

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自定义类,如图:

iOS 自定义控件在Xib中属性显示和效果实时渲染_第3张图片

你可能感兴趣的:(iOS 自定义控件在Xib中属性显示和效果实时渲染)