加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift UI专项训练8 展示数据

发布时间:2020-12-14 02:22:44 所属栏目:百科 来源:网络整理
导读:现在我想要点击表单中的条目,进行标记,再次点击以取消,那么该如何做呢?依然使用的是tableView的重载方法,在 Restaurant中新增一个isCollected的值表示是否收藏,然后回到RestaurantListViewController中,新增: override func tableView(tableView: UI

现在我想要点击表单中的条目,进行标记,再次点击以取消,那么该如何做呢?依然使用的是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)//删除列表行,其他行向上推
            
        }
    }
大家可以试下效果

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读