開始用Swift開發iOS 10 - 16 介紹靜態Table Views,UIImagePickerController和NSLayoutConstraint

繼續上一篇開始用Swift開發iOS 10 - 15 使用地圖,這一篇通過添加一個新建Restaurant頁面來介紹靜態Table Views,UIImagePickerControllerNSLayoutConstraint。靜態Table Views就是固定cell數目的Table Views;UIImagePickerController用來從設備圖片庫中獲取圖片;NSLayoutConstraint就是約束類,用來用代碼形式添加約束。

添加新的Table View Controller

  • 拖動一個Table View Controller到SB中。

  • 修改成Table Viewcontentstatic cells

  • 選中Table View Section,修改Rows成5。

  • 下載 [圖片] (http://www.appcoda.com/resources/swift3/photoicons.zip),拖進Assets

  • 修改第一個Cell高度為250。添加Image Viewimagephotoalbum,大小64*64,水平和垂直居中。

  • 第二個cell高度為72。添加一個Label文本NAME。添加一個Text Field,placeholderRestaurant Nameborder stylenone,寬度為339。添加適當約束。

  • 第三個和第四個Cell與第二個類似,Label文本分別為TYPE LOCATIONText Fieldplaceholder 分別為Restaurant TypeRestaurant Location

  • 第五個 高度為72。 添加一個Label文本Have You Been Here 。添加兩個Buttontitle分別為YESNO,字體顏色都為white,背景顏色分別為redgray

添加segue

  • Food Pin Controller的Navigation bar的右邊添加一個bar button itemSystem ItemAdd

  • 把上面新建是我table view controller內嵌在一個Navigation controller中,選中table view controller,在菜單欄中選擇Editor > Embed in > Navigation Controller,設置其navigation bar的titleNew Restaurant

  • 關聯Add按鈕和New Restaurant Controller的Navigation controller,segue類型present modally,identifieraddRestaurant

  • New Restaurant Controller的Navigation bar的左邊添加一個bar button itemSystem ItemCanceltintwhite

  • RestaurantTableViewController中添加unwind segue的action。用control-drag關聯。

@IBAction func unwindToHomeScreen(segue:UIStoryboardSegue) {
}

使用UIImagePickerController調用相冊

  • 新建AddRestaurantController,繼承至UITableViewController。關聯New Restaurant Controller
  • 刪除除了viewDidLoad方法的其他方法,靜態類型不需要了。
  • 添加tableView(_:didSelectRowAt:)
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
        IndexPath) {
        if indexPath.row == 0 {
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
                let imagePicker = UIImagePickerController()
                imagePicker.allowsEditing = false
                imagePicker.sourceType = .photoLibrary
                present(imagePicker, animated: true, completion: nil)
            }
        }
    }

選擇第一個cell,也就是圖片,通過isSourceTypeAvailable方法判斷是否有圖庫可用。

  • Info.plist中添加使用圖庫的請求描述, Privacy - Photo Library Usage Description -> You need to grant the app access to your photo library so you can pick your favorite restaurant photo.

實現UIImagePickerControllerDelegate協議

  • 添加UIImagePickerControllerDelegateUINavigationControllerDelegate
    class AddRestaurantController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

  • 添加接口@IBOutlet var photoImageView: UIImageView!,并關聯。

  • 添加函數imagePickerController(_:didFinishPickingMediaWithInfo:),當用戶從圖庫中選擇圖片時調用。

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            photoImageView.image = selectedImage
            photoImageView.contentMode = .scaleAspectFill
            photoImageView.clipsToBounds = true
        }
        
        dismiss(animated: TUREAD, completion: nil)
    }
  • tableView(_:didSelectRowAt:)中的imagePicker定義后添加:
    imagePicker.delegate = self

用代碼的方式定義約束

之前都是通過storyboard設置約束,其實也可以通過代碼的形式設置。

  • 之前的地圖的約束例子,storyboard 中的Map View.leading = leading等價于:
    let leadingConstraint = NSLayoutConstraint(item: mapView, attribute: NSLayoutAttribute.leading, relatedBy: .equal, toItem: mapView.superview, attribute: .leading, multiplier: 1, constant: 0)
    leadingConstraint.isActive = true

  • 在添加imagePickerController(_:didFinishPickingMediaWithInfo:)dismiss(animated: true, completion: nil)之前添加4個約束代碼。

let leadingConstraint = NSLayoutConstraint(item: photoImageView, attribute: .leading, relatedBy: .equal, toItem: photoImageView.superview, attribute: .leading, multiplier: 1, constant: 0)
        leadingConstraint.isActive = true
        
        let trailingConstrain = NSLayoutConstraint(item: photoImageView, attribute: .trailing, relatedBy: .equal, toItem: photoImageView.superview, attribute: .trailing, multiplier: 1, constant: 0)
        trailingConstrain.isActive = true
        
        let topConstraint = NSLayoutConstraint(item: photoImageView, attribute: .top, relatedBy: .equal, toItem: photoImageView.superview, attribute: .top, multiplier: 1, constant: 0)
        
        let buttomConstraint = NSLayoutConstraint(item: photoImageView, attribute: .bottom, relatedBy: .equal, toItem: photoImageView.superview, attribute: .bottom, multiplier: 1, constant: 0)

添加約束前后對比:


Exercise:驗證添加數據

  • New Restaurant Controller的Navigation controller的有右上角添加Save按鈕。
  • AddRestaurantController中添加五個接口和一個變量,并關聯。
    @IBOutlet var nameTextField:UITextField!
    @IBOutlet var typeTextField:UITextField!
    @IBOutlet var locationTextField:UITextField!
    @IBOutlet var yesButton:UIButton!
    @IBOutlet var noButton:UIButton!
     var isVisited: Bool = true
  • 添加一個Action,關聯save按鈕。
    @IBAction func save(_ sender: Any) {
        
        if (nameTextField.text?.isEmpty)! || (typeTextField.text?.isEmpty)! || (locationTextField.text?.isEmpty)! {
            let alertController = UIAlertController(title: "Oops", message: "We can't proceed because one of the fields is blank....", preferredStyle: .alert)
            let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alertController.addAction(alertAction)
            present(alertController, animated: true, completion: nil)
            
        } else {
            print(nameTextField.text, typeTextField.text, locationTextField.text, isVisited)
            dismiss(animated: true, completion: nil)
    //            performSegue(withIdentifier: "unwindToHomeScreen", sender: self)
        }
    }

去除** Add Restaurant view controller**回到主界面有兩種方法,一是dismiss(animated: true, completion: nil),而是利用unwind segue。

  • 添加一個Action toggleBeenHereButton:,用于yesButton和noButton的操作。
    @IBAction func toggleBeenHereButton(sender: UIButton) {
        if sender == yesButton {
            isVisited = true
            yesButton.backgroundColor = UIColor.red
            noButton.backgroundColor = UIColor.gray
        } else {
            isVisited = false
            yesButton.backgroundColor = UIColor.gray
            noButton.backgroundColor = UIColor.red
        }
    }

代碼

Beginning-iOS-Programming-with-Swift

說明

此文是學習appcode網站出的一本書 《Beginning iOS 10 Programming with Swift》 的一篇記錄

系列文章目錄

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容