使用扩展名创建自定义UIButton

时间:2016-12-15 12:54:47

标签: ios swift xcode swift3

我是iOS和Swift的新手,我需要一些帮助。

我想创建自定义UIButton

这就是我做的事情

protocol ButtonProtocol {}


extension ButtonProtocol where Self: UIButton {

    func addOrangeButton(){
        layer.cornerRadius = 8
        layer.backgroundColor = UIColor(netHex:ButtonColor.orange).cgColor
    }
}

我希望所有的params来自这里,它们是cornerRadius,backgrounColor,highlightColor,textColor,size等......

我想用这种方式bcoz可能以后按钮颜色会改变我会直接从一个地方改变它。

但我不明白什么是图层我怎么能把它作为UIButton?

有人能告诉我应该采取哪种方式?

4 个答案:

答案 0 :(得分:2)

您可以创建UIButton的子类,为您的按钮添加自己的自定义外观。像这样

import UIKit

protocol DVButtonCustomMethods: class {
func customize()
}

class DVButton: UIButton {
var indexPath: IndexPath?

override init(frame: CGRect) {
    super.init(frame: frame)
    customize()// To set the button color and text size
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    customize()// To set the button color and text size
}

override func layoutSubviews() {
    super.layoutSubviews()
    customize()
}

}

extension DVButton: DVButtonCustomMethods {
func customize() {
    layer.cornerRadius = self.frame.size.height / 2
    backgroundColor = UIColor.white
    tintColor = UIColor.red
    titleLabel?.textColor = UIColor.black
    clipsToBounds = true
}
}

现在需要做的是,在界面构建器中创建一个按钮,并将subClass指定为其类。多数民众赞成所有一切都会随着你想要的改变如果你想改变按钮颜色,只需改变你的子类,它将影响所有分配你的子类的按钮。

为您的按钮分配子类:请参阅下图

enter image description here

感谢:)

答案 1 :(得分:2)

您定义扩展程序的方式无法让您在UIButton实例中使用它如此简单。

因此,您可以决定是否扩展UIButton以符合协议,或者您可以创建UIButton

的子类
// in this way you can use the `addOrangeButton` method anywhere
extension UIButton: ButtonProtocol {}

// in this way your new subclass contains the addOrangeButton definition
// and a normal UIButton cannot access that method
final class OrangeButton: UIButton, ButtonProtocol {

    func setupButton() {
        addOrangeButton()
    }
}

答案 2 :(得分:0)

试试这个:

class func CutomeButton(bgColor: UIColor,corRadius: Float,hgColor: UIColor, textColor: UIColor, size: CGSize, titleText: String) -> UIButton {
    let button = UIButton()
    button.layer.cornerRadius = CGFloat(corRadius)
    button.backgroundColor = bgColor
    button.setTitleColor(textColor, for: .normal)
    button.frame.size = size
    button.setTitle(titleText, for: .normal)
    return button
}

答案 3 :(得分:0)

如果我理解得很好,你想修改一个带有特定参数的UIButton,让我告诉你我该怎么做:

extension UIButton
{
    func setRadius(radius:CGFloat) {
        self.layer.cornerRadius = radius
    }
}

将其用作以下内容:

yourButton.setRadius(radius: 15)