Swift學習筆記一 hello world
阿新 • • 發佈:2018-12-09
學習任何語言都是從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 ,讓我們看下效果