开始用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》 的一篇记录

系列文章目录

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容