Swift-UIKit-UIButton

2021-04-29  本文已影响0人  Vicent_Z

1.描述

A control that executes your custom code in response to user interactions.(一个可以用自定义代码响应用户交互的控制器)

@interface UIButton : UIControl
image.png

按钮使用注意事项:

按钮有五种状态,这些状态下的样式可以分别设置

按钮展示内容通常由三部分构成:backgroundImage,title,image

image.png

我们可以通过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

上一篇 下一篇

猜你喜欢

热点阅读