我在 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 中设置这些属性时,它就起作用了。为什么它不适用于类(class)?
最佳答案
改为编写此代码:-
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
在layoutSubviews()()中写入setUpView()
例如:-
override func layoutSubviews()() {
super.layoutSubviews()()
setupView()
}
关于ios - 如何将自定义类设置为以编程方式创建的 UIButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44340587/