1.描述
A control that executes your custom code in response to user interactions.(一个可以用自定义代码响应用户交互的控制器)
@interface UIButton : UIControl
按钮使用注意事项:
- 创建时候需要指定其类型:系统类型/用户自定义类型--通过buttonWithType:方法指定
- 需要设置标题或者图片,设置按钮合适的大小来适应内容
- 关联一个或者多个action方法:通过使用(addTarget:action:for:ControlEvents:)方法或者通过IB设置
- 设置自动约束布局
按钮有五种状态,这些状态下的样式可以分别设置
- default 按钮创建后未接收任何用户交互情况下
- highlighted 用户点击情况下的样式
- focused
- selected
- disabled
按钮展示内容通常由三部分构成:backgroundImage,title,image
我们可以通过titleEdgeInsets来单独设置标题的内边距,使用imageEdgeInsets来设置图片的内边距,还可以通过contentEdgeInsets设置整个内容的内边距(包含了title和image).
关于insets详细请参阅:
https://blog.csdn.net/u012089671/article/details/73920005
2.代码示例
import UIKit
class ViewController: UIViewController {
var myButton : UIButton = UIButton.init(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.myButton.setTitle("代码编写的按钮", for: .normal)
self.myButton.setTitleColor(.black, for: .normal)
self.myButton.translatesAutoresizingMaskIntoConstraints = false
self.myButton.setTitleColor(.systemBlue, for: .highlighted)
self.myButton.setTitleColor(.systemRed, for: .selected)
self.view.addSubview(self.myButton)
self.myButton.addTarget(self, action: #selector(codeAction(_:)), for: .touchUpInside)
let constraintV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-350-[myButton]", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["myButton" : self.myButton])
let constraintH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[myButton]-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["myButton" : self.myButton])
self.view.addConstraints(constraintV)
self.view.addConstraints(constraintH)
}
@IBAction func ibAction(_ sender: Any) {
print("IB中点击的事件\(sender)")
}
@objc func codeAction(_ sender: Any) {
print("代码点击事件\(sender)")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
self.myButton.isSelected = !self.myButton.isSelected
}
}
}
- 工程下载地址:
https://github.com/DeveloperZhang/SwiftStudyDemo
3.总结
UIButton是一个最基础常见的视图类,可以参考文档进行深入学习:UIKit->Views and Controls->UIButton