天天看點

Swift學習筆記一 hello world

學習任何語言都是從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 ,讓我們看下效果

Swift學習筆記一 hello world