Swift學習的第一個demo,講解了一些常用的知識點

來源:互聯網
上載者:User

標籤:==   height   source   方法   err   --   resource   ide   背景色   

/**

 1. OC [UIView alloc] initWithXXX:]

    Swift UIView(XXX:)

 

    類名() == alloc / init 等價

 

 2. 類方法

    OC [UIColor redColor]

    Swift UIColor.red

 

 3. 訪問當前對象的屬性,可以不使用‘self.’

    建議:都不用,在編譯器提示的時候,在添加,會對‘語境’有更好地體會

    原因:閉包(類似於OC中的block),需要使用‘self.‘

 

 4. 沒有’;‘

    ’;‘ 的目的是分割語句的,在Swift中,預設不需要。多個語句在一行的時候需要。

 

 5. 枚舉類型

    OC UIButtonTypeContactAdd

    Swift .contactAdd

 

 6. 監聽方法

    OC @selector

    Swift #selector() -- 3.0 有沒有參數都不需要加‘:’,調試加‘:‘也是可以的,具體看下面demo

          "clickMe","clickMe:" -- 2.0

 

 7. 增加文檔注釋快速鍵 option + cmd + /

 

 8. 顯示顏色面板 color + 斷行符號

 

 9. 取消了先行編譯指令

 */

 

class ViewController: UIViewController

{

    // MARK: - 視圖生命週期

    // MARK: 視圖載入完成

    override func viewDidLoad()

    {

        super.viewDidLoad()

        

        // 多個語句在一行就需要‘;‘隔開。單個語句預設不需要’;‘

        let a = 10; let b = 20

        print("a=\(a); b=\(b)")

        

        // 1. 建立一個視圖

        let v = UIView(frame: CGRect(x: 20, y: 40, width: 100, height: 200))

        

        // 設定背景色

        v.backgroundColor = UIColor.red // TODO: 應該設定新的顏色

//        v.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)

        

        // 添加到當前視圖

        view.addSubview(v)

        

        // 2. 建立一個按鈕

        let btn = UIButton(type: .contactAdd);

        btn.frame = CGRect(x: 0, y: 0, width: 60, height: 30)

        btn.center = CGPoint(x: v.frame.size.width * 0.5, y: v.frame.size.height * 0.5)

        // 方法 clickMe 不帶參數的寫法

        btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)

        

        // 方法 clickMe(btn: UIButton) 帶參數的下面兩種寫法都可以,調試沒有發現問題

        btn.addTarget(self, action: #selector(clickMe1(btn:)), for: .touchUpInside)

        btn.addTarget(self, action: #selector(clickMe1), for: .touchUpInside);

        v.addSubview(btn)

        

        let lv = UIImageView(image: #imageLiteral(resourceName: "contact_checked")); // FIXME: 應該更改映像

        view.addSubview(lv)

        

        

    }

    

    func clickMe() -> ()

    {

        print(#function)

        print("hehe")

    }

    

    func clickMe1(btn: UIButton) -> ()

    {

        print(#function)

        print("hehe")

        print("btn=\(btn)")

    }

}

Swift學習的第一個demo,講解了一些常用的知識點

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.