需求:創(chuàng)建UIView對象,并且在UIView中添加UIButton
1.創(chuàng)建UIView
let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
let view : UIView = UIView(frame: rect)
2.設(shè)置UIView的屬性
view.backgroundColor = UIColor.red
3.創(chuàng)建UIButton對象
let btn : UIButton = UIButton()
4.設(shè)置btn的屬性
//4.1設(shè)置btn的frame
btn.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
//4.2設(shè)置btn的背景顏色
btn.backgroundColor = UIColor.yellow
//4.3設(shè)置btn的文字
//Swift枚舉類型
//方式一:如果可以根據(jù)上下文語法推算出枚舉類型,可以直接.具體類型
btn.setTitle("點我", for: .normal)
//方式二:如果上下文語法無法推斷出類型,枚舉類型.具體類型
btn.setTitle("你牛", for: UIControlState.highlighted)
5.將btn添加到UIView中
view.addSubview(btn)