草庐IT

ios - 根据 API 的结果选择 Tableview 单元格

coder 2023-09-14 原文

如何通过字符串传递上一个选定的单元格。从 API 我通过“|”得到结果分开,然后我在删除分隔符后将其放回 array 中。但是如何将结果传递到 tableView 中,它将根据结果选择 tableview 单元格。

这是我如何进行选择并将结果保存到数组中的虚拟代码。

class TableViewController: UITableViewController
{
let limit = 5
var lastSelectedIndexPath = NSIndexPath(forRow: -1, inSection: 0)
    var genreList = ["A","B","C","D","E","F","G","H"]
var stringRepresentation = String()
var result = [String]()
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) 

    // Configure the cell...
    cell.textLabel!.text = genreList[indexPath.row]

    if cell.selected
    {
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryType.None
    }
    return cell
}


override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
    if let sr = tableView.indexPathsForSelectedRows {
        if sr.count == limit {
            let alertController = UIAlertController(title: "Oops", message:
                "You are limited to \(limit) selections", preferredStyle: .Alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: {action in
            }))
            self.presentViewController(alertController, animated: true, completion: nil)

            return nil
        }

    }

    return indexPath
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    print("selected  \(genreList[indexPath.row])")

    let cell = tableView.cellForRowAtIndexPath(indexPath)

    if cell!.selected == true
    {
        cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
        result.append((cell?.textLabel?.text)!)
        print(result)
    }
    else
    {

        cell!.accessoryType = UITableViewCellAccessoryType.None
        print(result)
    }
}


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

    let deselectedCell = tableView.cellForRowAtIndexPath(indexPath)

    result = result.filter { $0 != deselectedCell?.textLabel?.text }

    stringRepresentation = result.joinWithSeparator("|") // "1-2-3"

    print(stringRepresentation)

    deselectedCell!.accessoryType = UITableViewCellAccessoryType.None

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return genreList.count
}

}

最佳答案

尝试像这样选择单元格,为此使用您的result数组

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)

    // Configure the cell...
    cell.textLabel!.text = genreList[indexPath.row]
    if result.contains(genreList[indexPath.row])
    {
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryType.None
    }
    return cell
}      

现在像这样改变didSelectRowAtIndexPath

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{   
     tableView.deselectRowAtIndexPath(indexPath, animated: true)
     if (self.result.count != limit) {   
         if (self.result.contains(genreList[indexPath.row])) {
             let index = self.result.indexOf(genreList[indexPath.row])
             self.result.removeAtIndex(index)
         }
         else {
             self.result.append(genreList[indexPath.row])
         }
     }
     else {
         if (self.result.contains(genreList[indexPath.row])) {
             let index = self.result.indexOf(genreList[indexPath.row])
             self.result.removeAtIndex(index)   
         }
         else {
             let alertController = UIAlertController(title: "Oops", message:
            "You are limited to \(limit) selections", preferredStyle: .Alert)
             alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: {action in
         }))
             self.presentViewController(alertController, animated: true, completion: nil)
         }
     }
     stringRepresentation = result.joinWithSeparator("|")
     self.tableView.reloadData()
}

注意:ViewController 中删除 willSelectRowAtIndexPath 方法,现在不需要该方法了。

关于ios - 根据 API 的结果选择 Tableview 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38759002/

有关ios - 根据 API 的结果选择 Tableview 单元格的更多相关文章

  1. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. ruby-on-rails - ActionController::RoutingError: 未初始化常量 Api::V1::ApiController - 2

    我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. ruby - Rails 3 的 RGB 颜色选择器 - 2

    状态:我正在构建一个应用程序,其中需要一个可供用户选择颜色的字段,该字段将包含RGB颜色代码字符串。我已经测试了一个看起来很漂亮但效果不佳的。它是“挑剔的颜色”,并托管在此存储库中:https://github.com/Astorsoft/picky-color.在这里我打开一个关于它的一些问题的问题。问题:请建议我在Rails3应用程序中使用一些颜色选择器。 最佳答案 也许页面上的列表jQueryUIDevelopment:ColorPicker为您提供开箱即用的产品。原因是jQuery现在包含在Rails3应用程序中,因此使用基

  6. ruby-on-rails - Prawn - 表格单元格内的链接 - 2

    我正在尝试用Prawn生成PDF。在我的PDF模板中,我有带单元格的表格。在其中一个单元格中,我有一个电子邮件地址:cell_email=pdf.make_cell(:content=>booking.user_email,:border_width=>0)我想让电子邮件链接到“mailto”链接。我知道我可以这样链接:pdf.formatted_text([{:text=>booking.user_email,:link=>"mailto:#{booking.user_email}"}])但是将这两行组合起来(将格式化文本作为内容)不起作用:cell_email=pdf.make_c

  7. 报告回顾丨模型进化狂飙,DetectGPT能否识别最新模型生成结果? - 2

    导读语言模型给我们的生产生活带来了极大便利,但同时不少人也利用他们从事作弊工作。如何规避这些难辨真伪的文字所产生的负面影响也成为一大难题。在3月9日智源Live第33期活动「DetectGPT:判断文本是否为机器生成的工具」中,主讲人Eric为我们讲解了DetectGPT工作背后的思路——一种基于概率曲率检测的用于检测模型生成文本的工具,它可以帮助我们更好地分辨文章的来源和可信度,对保护信息真实、防止欺诈等方面具有重要意义。本次报告主要围绕其功能,实现和效果等展开。(文末点击“阅读原文”,查看活动回放。)Ericmitchell斯坦福大学计算机系四年级博士生,由ChelseaFinn和Chri

  8. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  9. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  10. ruby-on-rails - Mandrill API 模板 - 2

    我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h

随机推荐