1. 新增 Project
Create a new Xcode project > Single View Application (iOS)
2. Project Settings
Product Name / Team / Organization Name / Organization Identifier / (Bundle Identifier) / Language (Swift) / Devices (iPhone) / Use Core Data (none) / Include Unit Tests (none) / Include UI Tests (none)
3. Save Project Settings
4. 點選 Main.storyboard,拖曳一個 Button至 View Controller 上,更改文字為 Hello World!
5. 新增 UI / Code 連接點 @IBAction : showMessage
點選 Button,按 Control 鍵不放,拖曳至 ViewController 的 Icon 中
6. 在 Send Events 中,點選 showMessage,此時可在 Code 中 出現圓圈的連接點
7. 新增 showMessage() 的 Code
//
// ViewController.swift
// HelloWorldDemo
//
// Created by Elvis Meng on 2017/3/23.
// Copyright © 2017年 Elvis Meng. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showMessage(){
print("Hello World!")
}
}
8. 在模擬 iPhone 中,點選 Hello World! 這Button,會顯示 Hello World ! 這字串在 Debug 視窗中
//
// ViewController.swift
// HelloWorldDemo
//
// Created by Elvis Meng on 2017/3/23.
// Copyright © 2017年 Elvis Meng. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showMessage(){
//print("Hello World!")
let alertController = UIAlertController(title: "Alert!", message: "Hello World !", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
10. 測試結果:
結論:
這是很簡單練習,重點在 Xcode 開發環境熟悉,以及增加 Button 後 UI / Code 如何連接 connection。
點選 Button 後,會觸發 showMessage() 事件。 我們要實作此 code
/end
沒有留言:
張貼留言