Swift_UIButton

时间:2023-03-09 04:14:51
Swift_UIButton

1.初始化

        /**
UIButtonType.system:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
UIButtonType.contactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.detailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.infoDark:为感叹号“!”圆形按钮
UIButtonType.infoLight:为感叹号“!”圆形按钮
(注意:自ios7起,infoDark、infoLight、detailDisclosure效果都是一样的)
*/
let buttonOne = UIButton.init(type: UIButtonType.custom)

2. 设置

        /**
normal
highlighted
disabled
selected
*/
buttonOne.setTitle("这个是一个button", for: UIControlState.normal)
buttonOne.setImage(UIImage.init(named: "1.jpg"), for: UIControlState.normal) // 设置背景颜色
buttonOne.setBackgroundImage(UIImage.init(named: ""), for: UIControlState.normal) // 点击事件
buttonOne.addTarget(self, action: #selector(buttonOneClicked), for: UIControlEvents.touchUpInside)

3.代码

import UIKit

let kScreenWidth = UIScreen.main.bounds.size.width

class ViewController: UIViewController {

    override func viewDidLoad() {
super.viewDidLoad() self.addButtonOne()
} func addButtonOne() { self.view.addSubview(buttonOne)
} func buttonOneClicked() {
print("点击了")
} // 懒加载一个UIButton
lazy var buttonOne: UIButton = { /**
UIButtonType.system:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
UIButtonType.contactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.detailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
UIButtonType.infoDark:为感叹号“!”圆形按钮
UIButtonType.infoLight:为感叹号“!”圆形按钮
(注意:自ios7起,infoDark、infoLight、detailDisclosure效果都是一样的)
*/
let buttonOne = UIButton.init(type: UIButtonType.custom) buttonOne.frame = CGRect.init(x: , y: , width: kScreenWidth - , height: )
buttonOne.backgroundColor = UIColor.red /**
normal
highlighted
disabled
selected
*/
buttonOne.setTitle("这个是一个button", for: UIControlState.normal)
buttonOne.setImage(UIImage.init(named: "1.jpg"), for: UIControlState.normal) // 设置背景颜色
buttonOne.setBackgroundImage(UIImage.init(named: ""), for: UIControlState.normal) // 点击事件
buttonOne.addTarget(self, action: #selector(buttonOneClicked), for: UIControlEvents.touchUpInside) return buttonOne
}()
}