Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Swift - 给TableView添加编辑功能(删除,插入)

Swift - 给TableView添加编辑功能(删除,插入)

作者头像
Python疯子
发布于 2018-09-06 08:03:57
发布于 2018-09-06 08:03:57
3.3K00
代码可运行
举报
文章被收录于专栏:Python疯子Python疯子
运行总次数:0
代码可运行

1,下面的样例是给表格UITableView添加编辑功能: (1)给表格添加长按功能,长按后表格进入编辑状态 (2)在编辑状态下,第一个分组处于删除状态,第二个分组处于插入状态 (3)点击删除图标,删除对应条目 (4)点击添加图标,插入一条新数据

5819d62098010.png

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import UIKit
class ViewController: UIViewController ,UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
 
var tableView:UITableView!
var allNames:Dictionary<Int, [String]>!
var addHeaders:[String]!
 
 
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    allNames =
        [
            0:[String](["UILabel 标签", "UITextField 文本框", "UIButton 按钮"]),
            1:[String](["UIDatePiker 日期选择器", "TableView 表格视图", "UIToolbar 工具条", "UIWebView 浏览器"])
    ]
     
    print(allNames)
     
    addHeaders = ["常见 UIKit 控件","高级 UIKit 控件"]
    // 创建表格
    tableView = UITableView.init(frame: self.view.frame, style: UITableViewStyle.grouped)
    tableView.delegate = self
    tableView.dataSource = self
    self.view .addSubview(tableView)
     
    // 注册cell
    tableView .register(UITableViewCell.self, forCellReuseIdentifier: "cell")
     
    // 创建表头标签
    let headerLabel = UILabel.init(frame: CGRect(x:0, y:20, width:375, height:30))
    headerLabel.backgroundColor = UIColor.yellow
    headerLabel.textColor = UIColor.red
    headerLabel.numberOfLines = 0
    headerLabel.lineBreakMode = .byWordWrapping
    headerLabel.text = "高级 UIKit"
    headerLabel.textAlignment = NSTextAlignment.center
    headerLabel.font = UIFont.systemFont(ofSize: 15)
    tableView.tableHeaderView = headerLabel
     
    let longPress = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressAction))
    longPress.delegate = self
    longPress.minimumPressDuration = 1
    tableView .addGestureRecognizer(longPress)
}
 
func longPressAction(recognizer:UILongPressGestureRecognizer)  {
     
    if recognizer.state == UIGestureRecognizerState.began {
        print("UIGestureRecognizerStateBegan");
    }
    if recognizer.state == UIGestureRecognizerState.changed {
        print("UIGestureRecognizerStateChanged");
    }
    if recognizer.state == UIGestureRecognizerState.ended {
        print("UIGestureRecognizerStateEnded");
         
        if tableView.isEditing == true {
            tableView.isEditing = false
        }
        else
        {
            tableView.isEditing = true
        }
    }
}
 
// 创建分区
func numberOfSections(in tableView: UITableView) -> Int {
    return allNames.count
}
 
// 每个分区的行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return allNames[section]!.count
     
}
 
// 分区头部显示
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return addHeaders[section]
}
 
// 分区尾部显示
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
    let data = allNames[section]
    return "有\(data!.count)个控件"
}
 
// 显示cell内容
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let identify = "cell"
     
    let secno = indexPath.section
    let data = allNames[secno]
    var cell = UITableViewCell()
    cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: identify)
    if secno == 0 {
        cell.accessoryType = .disclosureIndicator
        cell.textLabel?.text = data?[indexPath.row]
         
        cell.imageView?.image = UIImage(named:"bug")
         
        
    }
    else
    {
         
        cell.textLabel?.text = data?[indexPath.row]
        cell.detailTextLabel?.text = "\(data![indexPath.row])的详解"
        
    }
     
     return cell
}
 
// cell的选中事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     
    // 确定该分组的内容
    let str = allNames[indexPath.section]?[indexPath.row]
    print("str\(str)")
}
 
// 设置单元格的编辑的样式
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    if indexPath.section == 0 {
        return UITableViewCellEditingStyle.insert
    }
    else
    {
        return UITableViewCellEditingStyle.delete
    }
}
 
// 设置确认删除按钮的文字
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
    return "确认删除"
}
 
// 单元格编辑后的响应方法
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {
        self.allNames[indexPath.section]?.remove(at: indexPath.row)
        tableView.setEditing(false, animated: true)
    }
         
    else if editingStyle == UITableViewCellEditingStyle.insert
    {
        allNames[indexPath.section]?.insert("插入的", at: indexPath.row)
        tableView.setEditing(false, animated: true)
    }
     
    tableView.reloadData()
  }   
}

功能改进 (1)默认情况下所有单元格都无法进行滑动删除等编辑操作。 (2)长按表格进入编辑状态,所有单元格都可以进行删除操作。 (3)同时在编辑状态下,在下方会自动出现一个新增操作单元格。点击前面的加号,便会给数据集中添加一条新数据。

5819d525b834b.png

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import UIKit 
class ViewController: UIViewController ,UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {

var tableView:UITableView!
var allNames:Dictionary<Int, [String]>!
var addHeaders:[String]!
 
 
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
allNames =
[
    0:[String](["UILabel 标签", "UITextField 文本框", "UIButton 按钮"]),
    1:[String](["UIDatePiker 日期选择器", "TableView 表格视图", "UIToolbar 工具条", "UIWebView 浏览器"])
    ]
 
    print(allNames)
     
    addHeaders = ["常见 UIKit 控件","高级 UIKit 控件"]
    // 创建表格
    tableView = UITableView.init(frame: self.view.frame, style: UITableViewStyle.grouped)
    tableView.delegate = self
    tableView.dataSource = self
    self.view .addSubview(tableView)
     
    // 注册cell
    tableView .register(UITableViewCell.self, forCellReuseIdentifier: "cell")
     
    // 创建表头标签
    let headerLabel = UILabel.init(frame: CGRect(x:0, y:20, width:375, height:30))
    headerLabel.backgroundColor = UIColor.yellow
    headerLabel.textColor = UIColor.red
    headerLabel.numberOfLines = 0
    headerLabel.lineBreakMode = .byWordWrapping
    headerLabel.text = "高级 UIKit"
    headerLabel.textAlignment = NSTextAlignment.center
    headerLabel.font = UIFont.systemFont(ofSize: 15)
    tableView.tableHeaderView = headerLabel
 
    let longPress = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressAction))
    longPress.delegate = self
    longPress.minimumPressDuration = 1
    tableView .addGestureRecognizer(longPress)
}
 
func longPressAction(recognizer:UILongPressGestureRecognizer)  {
  
    if recognizer.state == UIGestureRecognizerState.began {
         print("UIGestureRecognizerStateBegan");
    }
    if recognizer.state == UIGestureRecognizerState.changed {
        print("UIGestureRecognizerStateChanged");
    }
    if recognizer.state == UIGestureRecognizerState.ended {
        print("UIGestureRecognizerStateEnded");
         
        if tableView.isEditing == true {
            tableView.isEditing = false
        }
        else
        {
            tableView.isEditing = true
        }
         
        tableView.reloadData()
    }
}
 
// 创建分区
func numberOfSections(in tableView: UITableView) -> Int {
    return allNames.count
}
 
// 每个分区的行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    var count =  allNames[section]!.count
     
    if tableView.isEditing {
        count += 1
    }
     
    return count
     
}
 
// 分区头部显示
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return addHeaders[section]
}

// 分区尾部显示
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
    let data = allNames[section]
    return "有\(data!.count)个控件"
}
 
// 显示cell内容
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let identify = "cell"
     
    let secno = indexPath.section
    let data = allNames[secno]
     
    var cell = UITableViewCell()
     
    if secno == 0 {
         
        cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: identify)
        if tableView.isEditing && indexPath.row == data?.count {
             cell.textLabel?.text = "添加新数据..."
        }
        else
        {
            cell.accessoryType = .disclosureIndicator
            cell.textLabel?.text = data?[indexPath.row]
            cell.imageView?.image = UIImage(named:"bug")
        }
    }
    else if secno == 1
    {
         cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: identify)
         
         
        if tableView.isEditing && indexPath.row == data?.count {
            cell.textLabel?.text = "添加新数据..."
        }
        else
        {
            cell.textLabel?.text = data?[indexPath.row]
            cell.detailTextLabel?.text = "\(data![indexPath.row])的详解"
        }
    }
     
  return cell
     
}
 
// cell的选中事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    // 确定该分组的内容
    let str = allNames[indexPath.section]?[indexPath.row]
    print("str\(str)")
}
 
// 设置单元格的编辑的样式
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    if indexPath.section == 0 {
        if tableView.isEditing == false {
            return UITableViewCellEditingStyle.none
        }
        else if indexPath.row == allNames[indexPath.section]?.count {
            return UITableViewCellEditingStyle.insert
        }else {
            return UITableViewCellEditingStyle.delete
        }

    }
    else
    {
    
        if tableView.isEditing == false {
            return UITableViewCellEditingStyle.none
        }
        else if indexPath.row == allNames[indexPath.section]?.count {
            return UITableViewCellEditingStyle.insert
        }else {
            return UITableViewCellEditingStyle.delete
        }
    }
}
 
// 设置确认删除按钮的文字
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
    return "确认删除"
}
 
// 单元格编辑后的响应方法
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {
        self.allNames[indexPath.section]?.remove(at: indexPath.row)
    }
     
    else if editingStyle == UITableViewCellEditingStyle.insert
    {
        allNames[indexPath.section]?.insert("插入的", at: indexPath.row)
    }
     
    tableView.reloadData()
}
 
 
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  } 
}

下载demo:https://github.com/silencesmile/Swift_UITableView_4

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016.11.03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
iOS18适配指南之UITableView
YungFan
2024/09/27
3400
iOS开发-搜索栏UISearchBar和UISearchController
最近项目中用到了搜索栏,所以在网上搜了一些相关的资料学习了一下,现在记录一下,iOS中的搜索栏实现起来相对简单一点,网上也有很多参考资料,不过靠谱的不是很多,很多都是iOS 8.0之前的实现,iOS 8.0上的实现貌似很少看到,看了一些其他人的代码,使用了一下UISearchController感觉还是非常不错的。好了不多说了 ,来点干货吧。 1 UISearchBar和UIDisplayController实现搜索 是网上最常见的也算是最简单的,也有使用Searh Bar Search Displa
roc
2018/03/30
2.5K0
iOS开发-搜索栏UISearchBar和UISearchController
iOS17适配指南之UIContentUnavailableView(一)
YungFan
2023/07/24
5570
iOS17适配指南之UIContentUnavailableView(一)
Swift playground可视化开发
可以在playground里面进行界面开发,虽然不推荐,但确实可以 需要引入 PlaygroundSupport PlaygroundPage.current.liveView是展示内容的那个view,将需要展示的内容赋值给它即可 应用:SwiftUI 是Xcode11中的新功能,要求macOS 10.15才可以开启预览功能,其实不升级系统,可以利用playground可视化开发来实现预览 import UIKit import PlaygroundSupport //UIViewController
YungFan
2019/08/01
9020
UITableView增加和删除、移动
1、在控制器上添加一个UITableView,  暂时该UITableView控件变量名命名为为tableView, 设置控件代理,实现控制器的UITableViewDataSource, UITableViewDelegate协议;
tandaxia
2018/09/27
2K0
UITableView增加和删除、移动
ios5开发-UITableView开启编辑功能
该例子添加UITableView编辑功能 具体功能如下 功能很简单但很实用  @implementation AppDelegate @synthesize window = _window; @s
阿新
2018/04/12
8250
ios5开发-UITableView开启编辑功能
iOS-TableView统一数据源代理
TableView 是 iOS 应用程序中非常通用的组件,几乎每一个界面都有一个TableView,而我们许多的代码都和TableView有关系,比如数据展示、更新TableView,一些响应选择事件等,而这些大多都会通过其代理函数来实现,所以在VC中我们通常需要实现大量TableView的代理函数,如下面这样
用户2215591
2018/08/02
9960
IOS UITableViewCell的删除和插入
----------------------------------------插入------------------------------------------- 1 import UIKit 2 3 class ViewController:UIViewController, UITableViewDataSource, UITableViewDelegate{ 4 5 var diablo3Level = [“普通模式”, “困难模式”, “高手模 式”, “大师模式”, “地狱模
用户5760343
2019/07/08
9570
IOS UITableViewCell的删除和插入
iOS·下载管理第三方框架初步调研
笔者目前比较关注的点是第三方框架中,删除指定下载任务的处理逻辑。 1.FGDownloader 地址 https://github.com/Insfgg99x/FGDownloader 移除任务示例 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
陈满iOS
2018/10/09
1K0
iOS·下载管理第三方框架初步调研
Swift 2.0 自定义cell和不同风格的cell
      昨天我们写了使用系统的cell怎样创建tableView,今天我们再细分一下,就是不同风格的cell,我们怎写代码。先自己创建一个cell,继承于UItableviewcell 我们看看 cell 里面的代码怎么写的,我现在把 整个 cell 代码展示出来。 import UIKit class HomeTableViewCell: UITableViewCell { let oneImage:UIImageView = UIImageView() ov
Mr.RisingSun
2018/01/09
1K0
Swift Reusable开源库使用
Reusable是一个在swift下使用的开源库。利用protocol extension结合泛型提供了一个优雅的方案来dequeueReusableCell。使用 根据类型获取cell让你的cell声明Reusable或NibReusable协议
赵哥窟
2020/08/20
1.3K0
UITableViewCell系列之(一)让你的cell支持二次编辑
关于UITableViewCell一些别具一个的样式和用法。很早就想系统的写一篇文章,文章中囊括开发中UITableViewcell的一些花样用法和奇葩用法。结果还是以简短的方式分享出来,因为没有太多
VV木公子
2018/06/05
7.9K0
swift demo1 tableview
代码如下: // // ViewController.swift // demo1_tableview // // Created by Alice_ss on 2018/2/24. // Copyright © 2018年 AC. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{ //定义一个tab
用户1219438
2018/03/29
8590
【swift学习笔记】三.使用xib自定义UITableViewCell
使用xib自定义tableviewCell看一下效果图 1.自定义列 新建一个xib文件 carTblCell,拖放一个UITableViewCell,再拖放一个图片和一个文本框到tableviewc
lpxxn
2018/01/31
2.1K0
【swift学习笔记】三.使用xib自定义UITableViewCell
Swift 学习Using Swift mix and match, network: 写rss读者
4. need a feed manager: FeedManager.swift
全栈程序员站长
2022/07/06
1.4K0
UITableView实现QQ好友列表实战(动态插入删除Cell)
实现选择 网上大部分的教程,都是基于修改section的hearderView来实现的,但是看QQ的好友列表,style是grouped,显然不是使用section的header来处理。使用section的hearderView来实现的,十分简单,网上也有很多源码和教程,只要刷新一下dataSource然后调用就可以了。不在本次讨论的范围之内。 - (void)reloadSections:(NSIndexSet *)sections 这次我直接使用grouped的cell来做父cell,点击后展开相应的子
xferris
2018/06/01
1.4K0
iOS一点点 - TableView 拼音序排序(汉字转拼音、简繁体转换、日文转罗马音等)
Introduction to ICU General Transforms Transform Rule Tutorial 使用ICU进行拼音转汉字暂时似乎也许可能是不太行的
Alan Zhang
2018/10/19
2.2K0
iOS一点点 - TableView 拼音序排序(汉字转拼音、简繁体转换、日文转罗马音等)
IOS UITableViewCell 移动单元格位置
1 import UIKit 2 3 class ViewController:UIViewController, UITableViewDataSource, UITableViewDelegate{ 4 5 var customers = [“[普通客户]冮炳林”, “[普通客户]扶伽 霖”, “[普通客户]冈皑冰”, 6 “[金牌客户]符博富”, “[普通客户]范姜臣华”] 7 8 override func viewDidLoad() { 9 super.viewDidLoad
用户5760343
2019/07/08
1.4K0
UITableView 编辑状态(删除、添加、移动)
----- TableView 删除和添加 ----- ** UITableView 编辑步骤 1.让 tableView 处于编辑状态 2.协议确定 1)确定 cell 是否处于编辑状态 2)设定 cell 的编辑样式(删除、添加) 3) 编辑状态进行提交** 开启编辑状态 //1.让 tableView 处于编辑状态 [tableView setEditing:YES animated:YES]; 如果
LeeCen
2018/10/11
1.6K0
UITableView 编辑状态(删除、添加、移动)
IOS UITableView 表格嵌套
自定义表格控件:CustomizeUITableViewCell.swif //自定义单元格,单元格高度动态调整 1 import UIKit 2 3 class CustomizeUITableViewCell:UITableViewCell, UITableViewDataSource, UITableViewDelegate { 4 5 var tableView:UITableView!; 6 var comments:[String] = [] 7 8 override init
用户5760343
2019/07/08
1.1K0
IOS UITableView 表格嵌套
推荐阅读
相关推荐
iOS18适配指南之UITableView
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验