用户众妙之门 發表於 2022-1-26 15:29:13

Swift实现表格视图单元格多选

<p>本文实例为大家分享了Swift实现表格视图单元格多选的具体代码,供大家参考,具体内容如下</p>
<h2>效果</h2>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202201/2022126141200845.gif?2022026141324" /></p>
<h2>前言</h2>
<p>这段时间比较忙,没太多的时间写博客,前段时间写了一些关于表格视图单选的文章,想着,一并把多选也做了,今天刚好有时间,去做这样一件事情。多选在我们的应用程序中也是常见的,比如消息的删除,群发联系人的选择,音乐的添加等等可能都会涉及到多选的需求,本文,我将模拟多选删除消息来讲讲多选的实现。</p>
<h2>原理</h2>
<p>多选删除其实很简单,并不复杂,我的思路就是创建一个数组,当用户选中某个单元格的时候,取到单元格上对应的数据,把它存入数组中,如果用户取消选中,直接将数据从数组中移除。当用户点击删除时,直接遍历数组,将表格视图数据源数组里面的与存选择数据的数组中的数据相对应一一删除,再刷新表格视图即可。</p>
<h2>实现</h2>
<p>界面搭建很简单,创建一个表格视图,添加导航栏,并在上面添加一个删除按钮,这里我就不细说了。</p>
<p>在<code>ViewController</code> 中,我们先声明几个属性,其中 <code>selectedDatas</code> 主要用于记录用户选择的数据。</p>
<div class="jb51code"><pre class="brush:cpp;">var tableView: UITableView?
var dataSource: ?
var selectedDatas: ?</pre></div>
<p>创建初始化方法,初始化属性,别忘了还需要在<code> ViewDidLoad()</code>中调用方法初始化方法。</p>
<div class="jb51code"><pre class="brush:cpp;">// MARK:Initialize methods
func initializeDatasource() {

    self.selectedDatas = []

    self.dataSource = []

    for index in 1...10 {
        index &lt; 10 ? self.dataSource?.append("消息0\(index)") : self.dataSource?.append("消息\(index)")
    }
}

func initializeUserInterface() {

    self.title = "消息"
    self.automaticallyAdjustsScrollViewInsets = false

    // Add delete navigation item
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "删除", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("respondsToBarButtonItem:"))

    // table view
    self.tableView = {
        let tableView = UITableView(frame: CGRectMake(0, 64, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)), style: UITableViewStyle.Plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.tableFooterView = UIView()
        return tableView
        }()
    self.view.addSubview(self.tableView!)   
}</pre></div>
<p>此时,系统会报警告,提示你没有遵守协议,因为我们在初始化表格视图的时候为其设置了代理和数据源,遵守协议,并实现协议方法,配置数据源。</p>
<div class="jb51code"><pre class="brush:cpp;">func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {

    return self.dataSource!.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {

    var cell: CustomTableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellReuseIdentifier") as? CustomTableViewCell
    if cell == nil {
        cell = CustomTableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "cellReuseIdentifier")
    }

    cell!.selectionStyle = UITableViewCellSelectionStyle.None
    cell!.textLabel?.text = self.dataSource!
    cell!.detailTextLabel?.text = "昨天 10-11"

    return cell!
}</pre></div>
<p>这里需要强调的是,表格视图的单元格是自定义的,在自定义单元格<code>(CustomTableViewCell)</code>中我只做了一个操作,就是根据单元格选中状态来切换图片的显示。</p>
<div class="jb51code"><pre class="brush:cpp;">override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    if selected {
        self.imageView?.image = UIImage(named: "iconfont-selected")
    }else {
        self.imageView?.image = UIImage(named: "iconfont-select")
    }
}</pre></div>
<p>现在运行程序,界面已经显示出来了,下面我们将开始处理多选删除的逻辑,当我们点击单元格的时候发现,只能单选啊?我要怎么去多选呢?此时我们需要在配置表格视图的地方设置 <code>allowsMultipleSelection</code> 属性,将其值设为 YES。</p>
<div class="jb51code"><pre class="brush:cpp;">tableView.allowsMultipleSelection = true</pre></div>
<p>接下来,实现代理方法 <code>didSelectRowAtIndexPath:</code> 与 <code>didDeselectRowAtIndexPath:</code>,这里我们将修改单元格选中与未选中状态下的颜色,只需根据参数<code>indexPath</code>获取到单元格,修改 <code>backgroundColor</code> 属性,并且,我们还需要获取单元格上的数据,去操作<code>selectedDatas</code>数组,具体实现如下。</p>
<div class="jb51code"><pre class="brush:cpp;">func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let cell = tableView.cellForRowAtIndexPath(indexPath)
    cell?.backgroundColor = UIColor.cyanColor()

    self.selectedDatas?.append((cell!.textLabel?.text)!)

}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

    let cell = tableView.cellForRowAtIndexPath(indexPath)
    cell?.backgroundColor = UIColor.whiteColor()

    let index = self.selectedDatas?.indexOf((cell?.textLabel?.text)!)
    self.selectedDatas?.removeAtIndex(index!)
}</pre></div>
<p>在 <code>didDeselectRowAtIndexPath:</code>方法中,我是根据表格视图单元格上的数据获取下标,再从数组中删除元素的,可能有的人会问,不能像OC一样调用<code>removeObject:</code>方法根据数据直接删除元素吗?并不能,因为Swift 提供的删除数组元素的方法中,大都是根据下标来删除数组元素的。</p>
<p>接下来,我们需要执行删除逻辑了,在删除按钮触发的方法中,我们要做的第一件事情就是异常处理,如果 <code>selectedDatas</code> 数组为空或者该数组并未初始化,我们无需再做删除处理,弹框提示即可。</p>
<div class="jb51code"><pre class="brush:cpp;">// Exception handling
if (self.selectedDatas == nil) || (self.selectedDatas?.isEmpty == true) {
    let alertController = UIAlertController(title: "温馨提示", message: "请选择您要删除的数据!", preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alertController, animated: true, completion: nil)
    return
}</pre></div>
<p>异常处理之后,我们需要遍历<code>selectedDatas</code>数组,然后根据该数组中的数据获取到该数据在数据源(<code>dataSource</code>)里的下标,最后再根据该下标将数据从数据源中删除。</p>
<div class="jb51code"><pre class="brush:cpp;">for data in self.selectedDatas! {

    // Get index with data
    let index = self.dataSource!.indexOf(data)

    // Delete data with index
    self.dataSource?.removeAtIndex(index!)
}</pre></div>
<p>现在我们只需要刷新表格视图即可,当然,<code>selectedDatas</code>数组我们也需要清空,以备下一次用户多选删除使用。</p>
<div class="jb51code"><pre class="brush:cpp;">self.tableView?.reloadData()

self.selectedDatas?.removeAll()</pre></div>
<p>为了提高用户体验,我们可以弹框提示用户删除成功,直接在后面加上以下代码。</p>
<div class="jb51code"><pre class="brush:cpp;">let alertController = UIAlertController(title: "温馨提示", message: "数据删除成功!", preferredStyle: UIAlertControllerStyle.Alert)

self.presentViewController(alertController, animated: true, completion: nil)


dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -&gt; Void in
    self.presentedViewController?.dismissViewControllerAnimated(true, completion: nil)
}</pre></div>
<p>代码中,我并未给弹出框添加<code>action</code> ,而是通过一个延迟调用,来让弹出框自动消失,这样就避免了用户再次点击弹出框按钮来隐藏,提升用户体验。</p>
<p>OK,到了这一步,基本已经实现了,但是有一个小瑕疵,那就是当我删除了单元格的时候,界面上某些单元格会呈现选中状态的背景颜色,解决办法非常简单,我们只需要在配置单元格的协议方法中加上这一句话即可。</p>
<div class="jb51code"><pre class="brush:cpp;">cell?.backgroundColor = UIColor.whiteColor()</pre></div>
<p>以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持琼殿技术社区。</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>swift framework使用OC 代码两种方式示例</li><li>SwiftUI中TabView组件的常规使用</li><li>SwiftUI自定义导航的方法实例</li><li>Swift踩坑实战之一个字符引发的Crash</li><li>swift语言AutoreleasePool原理及使用场景</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: Swift实现表格视图单元格多选