Fork me on GitHub

开始用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。
  • 下载 图片,拖进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关联。

    1
    2
    @IBAction func unwindToHomeScreen(segue:UIStoryboardSegue) {
    }

使用UIImagePickerController调用相册

  • 新建AddRestaurantController,继承至UITableViewController。关联New Restaurant Controller
  • 删除除了viewDidLoad方法的其他方法,静态类型不需要了。
  • 添加tableView(_:didSelectRowAt:)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    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:),当用户从图库中选择图片时调用。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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个约束代码。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    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中添加五个接口和一个变量,并关联。

    1
    2
    3
    4
    5
    6
    @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按钮。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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的操作。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @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》 的一篇记录


--------------------本文结束👨‍💻感谢您的阅读--------------------
坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文标题: 开始用Swift开发iOS 10 - 16 介绍静态Table Views,UIImagePickerController和NSLayoutConstraint
  • 本文作者: AndyRon
  • 发布时间: 2017年07月25日 - 00:00
  • 最后更新: 2019年09月03日 - 15:22
  • 本文链接: http://andyron.com/2017/beginning-ios-swift-16.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!
0%