以下是如何UIButton
在视图控制器 ( UIViewController
) 中实例化子类的简单示例。它在 Swift 4.2 下进行了测试。
// Subclassing UIButton //
import UIKit
class MyButton: UIButton {
var tintColor0: UIColor!
var tintColor1: UIColor!
var borderColor: UIColor!
var backColor: UIColor!
var cornerRadius: CGFloat!
required init(frame: CGRect, tintColor0: UIColor, tintColor1: UIColor, borderColor: UIColor, backColor: UIColor, cornerRadius: CGFloat, titleString: String) {
super.init(frame: frame)
self.tintColor0 = tintColor0
self.tintColor1 = tintColor1
self.borderColor = borderColor
self.backColor = backColor
self.cornerRadius = cornerRadius
self.setTitle(titleString, for: .normal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
self.setTitleColor(tintColor0, for: .normal)
self.setTitleColor(tintColor1, for: .highlighted)
self.layer.borderColor = borderColor.cgColor
self.layer.cornerRadius = cornerRadius
self.layer.borderWidth = 1.0
self.layer.backgroundColor = backColor.cgColor
}
}
// View controller //
import UIKit
class ViewController: UIViewController {
// MARK: - Variables
// MARK: - IBOutlet
// MARK: - IBAction
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
let buttonRect = CGRect(x: 20.0, y: 160.0, width: 100.0, height: 32.0)
let myButton = MyButton(frame: buttonRect, tintColor0: UIColor.black, tintColor1: UIColor.gray, borderColor: UIColor.orange, backColor: UIColor.white, cornerRadius: 8.0, titleString: "Hello")
myButton.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
view.addSubview(myButton)
}
@objc func buttonTapped(_ sender: UIButton) {
print("Hello!?")
}
}