2016-07-21 新增使用程式碼刻UI元件 2016-07-22 新增使用segue 2016-08-10 新增Switch button和Segmented Control, 修改segue用法 *2016-08-23 新增UIPickerView和UISearchController
UITableView:
ViewController 需要繼承UITableViewDataSource, UITableViewDelegate
加入func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {}
加入func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {}
上一個步驟中,使用tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)設定cell (cell要設定identifier)
最後,選取TableView,按住ctrl拖曳至View Controller並選取dataSource和delegate
額外設定:
修改section title
1 2 3 override func tableView (tableView : UITableView , titleForHeaderInSection section : Int ) -> String ? { return "Section \(section) " }
使用程式碼新增UI元件 以UIImageView為例
1 2 3 4 5 6 7 8 9 10 11 12 let image = UIImageView ()override func viewDidLayoutSubviews () { view.addSubview(image) image.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint .activateConstraints([ artwork.topAnchor.constraintEqualToAnchor(view.topAnchor), artwork.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor), artwork.rightAnchor.constraintEqualToAnchor(view.rightAnchor), artwork.leftAnchor.constraintEqualToAnchor(view.leftAnchor) ]) }
使用segue 在storyboard建立segue後。在Attribute inspector中,修改Identifier(例如命名為showMessageIdentifier),假如轉換到名為ImageViewController的ViewController
然後在view controller加入以下程式碼
1 2 3 4 5 6 override func prepareForSegue (segue : UIStoryboardSegue , sender : AnyObject ?) { if segue.identifier == "showMessageIdentifier" { let vc = segue.destinationViewController as! ImageViewController } }
1 2 3 4 5 if switchButton.on { } else { }
使用Segmented Control 可用selectedSegmentIndex判斷目前的選擇1 2 3 switch locationSegmentedControl.selectedSegmentIndex { }
UIPickerView
拉UIPickerView的outlet至ViewController
設定並實作delegate及dataSource
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class ViewController : UIViewController { @IBOutlet weak var locationPicker: UIPickerView ! var taipeiDistrictArray = ["中正區" , "中山區" ] override func viewDidLoad () { super .viewDidLoad() locationPicker.delegate = self locationPicker.dataSource = self } } extension ViewController : UIPickerViewDataSource { func numberOfComponentsInPickerView (pickerView : UIPickerView ) -> Int { return 1 } func pickerView (pickerView : UIPickerView , numberOfRowsInComponent component : Int ) -> Int { return taipeiDistrictArray.count } } extension ViewController : UIPickerViewDelegate { func pickerView (pickerView : UIPickerView , titleForRow row : Int , forComponent component : Int ) -> String ? { return taipeiDistrictArray[row] } }
參考來源:iOS & Swift Tutorial: UITableViewController