swift学习笔记--按钮样式
2020-05-31 本文已影响0人
迷夏湖
1 需求
屏幕背景设置为纯黑色,底部一排放几个按钮。按钮黑底白字白色边框,当点击按钮后,按钮变为白底黑字。
2 实现
很简单的需求,不过UIVIewController直接设置backgroundColor无效,需要定义一个UIView放上去,然后在UIView上加按钮即可。代码如下:
override func viewDidLoad() {
super.viewDidLoad()
wid = view.bounds.width
hei = view.bounds.height
// 直接设置view的backgroundColor不生效
myView = UIView(frame: CGRect(x: 0, y: 0, width: wid, height: hei))
myView.backgroundColor = UIColor.black
view.addSubview(myView)
// 底部按钮设置
setBottomBtn()
}
func setBottomBtn() {
let btnWid:CGFloat = (wid - 20*6)/5
let btnY:CGFloat = hei - btnX - btnHei
let btnNameArr = ["测试", "自强", "弘毅", "求是", "拓新"]
for i in 0..<btnNameArr.count {
let btn = UIButton(frame: CGRect(x: btnX*CGFloat(i+1) + btnWid*CGFloat(i), y: btnY, width: btnWid, height: btnHei))
decorateBtn(btn: btn, title: btnNameArr[i])
myView.addSubview(btn)
btn.addTarget(self, action: #selector(bottomBtnTap(btn:)), for: .touchUpInside)
}
}
@objc func bottomBtnTap(btn: UIButton) {
// 点击变化颜色
btn.setTitleColor(UIColor.black, for: .normal)
btn.backgroundColor = UIColor.white
}
// 给btn加样式
func decorateBtn(btn: UIButton, title: String) {
btn.setTitleColor(UIColor.white, for: .normal) // 按钮上文字颜色
btn.setTitle(title, for: .normal)
btn.contentHorizontalAlignment = .center
//btn1.backgroundColor = UIColor.blue // 按钮背景色
btn.layer.cornerRadius = 5 // 圆角
btn.clipsToBounds = true;
// 边框及颜色
btn.layer.borderWidth = 1;
btn.layer.borderColor = UIColor.white.cgColor
}