swift UI专项训练8 展示数据

现在我想要点击表单中的条目,进行标记,再次点击以取消,那么该如何做呢?依然使用的是tableView的重载方法,在

Restaurant中新增一个isCollected的值表示是否收藏,然后回到RestaurantListViewController中,新增:

   override func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
       let r1 = restaurantList[indexPath.row]//取出点击的行
        r1.isCollected = !r1.isCollected//单击后收藏状态取反
        tableView.deselectRowAtIndexPath(indexPath,animated: false)
        tableView.reloadData()
    }

但是运行的时候是没有反应的,虽然状态已经改了,但是没有体现到页面上,现在应该在页面上增加一个标记,更改后的控制cell的tableView方法如下:
 
    override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("PCell",forIndexPath: indexPath) as UITableViewCell
    let r1 = restaurantList[indexPath.row]
        // Configure the cell...
       cell.textLabel?.text = r1.name//行数
        if r1.isCollected{
            cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        } else {
            cell.accessoryType = UITableViewCellAccessoryType.None
        }
        return cell
    }

运行效果,点击条目:


再点一下就取消了,除了勾之外还有很多有趣的标识,大家可以试试。

导航上还有编辑按钮,现在我们来实现编辑功能。现在点击左边的编辑按钮是没反应的,我们需要在viewDidLoad中增加下面的语句:

 self.navigationItem.leftBarButtonItem = self.editButtonItem()
要让系统知道导航坐标的按钮是我们的编辑按钮,然后在控制器中加入一个新的方法setEditing,这个也是自动补全的,代码如下:
override func setEditing(editing: Bool,animated: Bool) {
        super.setEditing(editing,animated: true)//先实现父类的
        tableView.setEditing(editing,animated: true)
    }

现在我们再点击编辑按钮,效果如下:


点击完成会返回。点击左边的红色图标右侧会滑出删除按钮,点击按钮会删除当前行,只需要在控制器中新增一个方法就好,代码如下:

    override func tableView(tableView: UITableView,commitEditingStyle editingStyle: UITableViewCellEditingStyle,forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete{//如果是删除按钮
        restaurantList.removeAtIndex(indexPath.row)//先删除数组中的元素
            tableView.deleteRowsAtIndexPaths([indexPath],withRowAnimation: UITableViewRowAnimation.Top)//删除列表行,其他行向上推
            
        }
    }
大家可以试下效果

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...