【问题标题】:Need to display certain string elements in an array at the top of a UITableView in Swift需要在 Swift 中 UITableView 顶部的数组中显示某些字符串元素
【发布时间】:2016-07-16 04:15:52
【问题描述】:

我有一个 UITableView,它显示数组中的字符串列表。该数组按字母顺序排列,在 UITableView 的顶部是一个 UISearchController 栏。一切正常。但是,我需要对 UITableView 中显示的列表进行修改,其中集合中的某个子集显示在 UITableView 的顶部(并且该子集也应该按字母顺序排列)。但是,一旦用户在顶部的搜索过滤器中输入了一个字符,显示的字符串列表就无关紧要了。

例如,我有一个 UITableView,它按字母顺序显示员工列表。我想要做的是当 UITableView 加载时,而不是按字母顺序显示所有员工,我想首先按字母顺序列出经理,然后按字母顺序列出剩余的员工(即在经理之后)。

在 ViewController 中接收到的数组包含来自前一个 ViewController 的 UITableView,它发送这个已经按字母顺序排序的列表。换句话说,开始的数组是已经排序的。

【问题讨论】:

  • 一个数组应该是一个相同类型的有序集合,为什么不把经理和雇主分成两个独立的数组呢?这背后有什么原因吗?只是想知道
  • 它们在技术上属于同一类型(即字符串)。但是,我最初如何显示两个有序数组,并且一旦用户在搜索字段中输入字符,就会搜索两个区域的集合?

标签: ios arrays swift uitableview


【解决方案1】:

我假设您不想使用部分?您只是希望它们都在同一个部分中吗?

如果是这种情况,您可能需要进行一些预处理以将数组拆分为您的子集(在 viewDidLoad 或控制器生命周期开始时的其他地方):

self.managerArray = [AnyObject]() // you'll need a property to hold onto this new data source
self.employeeArray = [AnyObject]()

for employee: Employee in self.allEmployees {
    // assume allEmployees is the alphabetical array
    if employee.isManager {
        // your condition for determining the subset
        managerArray.append(employee)
    }
    else {
        employeeArray.append(employee)
    }
}

因为数组已经按字母顺序排列,所以也应该按字母顺序填充子数组(append 只是添加到下一个索引)。

然后,为了确保表格在以这种方式处理之前不会加载值,您需要这样做

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if self.employeeArray && self.managerArray {
        return self.employeeArray.count + self.managerArray.count
    }
    return 0
}

然后,您只需从self.managerArray 填充单元格,然后再移至self.employeeArray

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if indexPath.row < self.managerArray.count {
        var manager: Employee = self.managerArray[indexPath.row]
        // populate your cell info here
    }
    else {
            // else we've already filled in manager's time to start on employees
            // subtract the number of managers from the indexPath to start at beginning of employeeArray
        var employee: Employee = self.employeeArray[indexPath.row - self.managerArray.count]
        // populate cell here
    }
    return cell
}

然后当你搜索的时候,你可以像往常一样在原来的self.allEmployees数组上搜索。

【讨论】:

  • 问题是关于在 Swift 中做这件事,我猜是因为有 swift 标签。如果没有其他人先翻译,我明天会尝试翻译。
  • 哎呀,错过了 - 我认为应该这样做,但你能确认一下,因为我习惯了 obj-c
  • 这应该没有必要。该算法足够好,因为我知道 Objective-C,因此提出 Swift 等价物不是问题。
猜你喜欢
  • 1970-01-01
  • 2020-11-22
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-16
相关资源
最近更新 更多