如何设置自定义类以编程方式创建UIButton?

时间:2017-06-03 05:20:58

标签: ios swift uibutton

我在ViewController中以下列方式创建了一个按钮:

var userButton: Button!

override func viewDidLoad() {

    userButton = Button()
    userButton.frame = CGRect(x: self.view.frame.width / 2 + 90, y: 
    self.view.frame.height / 1.5 + 110, width: 100, height: 100)
    userButton.addTarget(self, action: #selector(MainController.userButtonTapped(sender:)), for: .touchUpInside)

    self.view.addSubview(userButton)
}

这是我创建的Button类:

import UIKit

@IBDesignable
class Button: UIButton {

// MARK: - PROPERTIES

@IBInspectable var cornerRadius: CGFloat = 3.0 {
    didSet {

        setupView()
    }
}

// MARK: - CONFIGURATION

override func awakeFromNib() {

    setupView()
}

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()

    setupView()
}

/**
 *  Sets default properties to the view.
 */
func setupView() {

    self.layer.cornerRadius = cornerRadius

    * Shadow properties */
    self.layer.shadowColor = SHADOW_COLOR.cgColor
    self.layer.shadowOpacity = 0.6
    self.layer.shadowRadius = 6.0
    self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
}
}

运行应用程序时,userButton没有在类中设置属性。但是,当我在ViewController中设置这些属性时,它可以工作。为什么它不适用于班级?

1 个答案:

答案 0 :(得分:2)

而是编写此代码: -

override func awakeFromNib() {
    super.awakeFromNib()
    setupView()
}

在layoutSubviews()()

中编写setUpView()

例如: -

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