学习任何语言都是从hello world开始的,哈哈哈
开始我的swift学习之旅
//这个好像就是类似于OC的懒加载 (个人观点--菜鸡观点)
fileprivate var helloBtn: UIButton = {
let helloBtn = UIButton(type:.custom) //初始化UIButton
helloBtn.frame = CGRect(x: 100, y: 100, width: 205, height: 50) //设置frame
helloBtn.backgroundColor = UIColor.blue //设置背景颜色
helloBtn.setTitle("欢迎", for: UIControlState.normal) //设置title (普通状态下)
helloBtn.setTitleColor(UIColor.white, for: .normal) //设置title的颜色 (普通状态下)
helloBtn.setTitle("hello world", for: UIControlState.selected) //设置title (点击状态下)
helloBtn.addTarget(self, action: #selector(helloBtnClick), for: .touchUpInside) //添加点击事件
return helloBtn
}()
至于我们需要实现什么效果,且等代码上完
初始化一个button OK了,就需要把它加载在View上显示出来
//这个方法相当于 OC里的 -(void)viewDidLoad;
override func viewDidLoad() {
super.viewDidLoad()
//在view上添加一个按钮
self.view .addSubview(helloBtn)
}
ok,还差一个点击事件的方法
extension ViewController{
//这个就是点击事件出发的方法
@objc fileprivate func helloBtnClick(sender :UIButton){
//改变状态
sender.isSelected = !sender.isSelected;
}
}
ok ,让我们看下效果