ios - 我如何能够创建一个 tableViewCell 以按字母顺序显示按文本字段添加的文本?

标签 ios arrays swift textfield

我使用文本字段将文本添加到 tableViewCell 中,但在 tableView 顶部的单元格中输入的单词顺序不是字母顺序。它是如何按字母顺序排列的?是否有任何内置方法可以执行此操作,或者我是否编写了一个方法?谢谢你!

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var myTextField: UITextField!
var stringArray = [String]()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return stringArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    cell.textLabel?.text = stringArray[indexPath.row]
    return cell
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    return true
}

@IBAction func AddButton(sender: UIButton) {
    stringArray.append(myTextField.text)
    myTextField.text = nil
    myTextField.resignFirstResponder()
    tableView.reloadData()
}

最佳答案

UITableView 只是向您显示数组中的相同字符串。您正在使用 append 方法,该方法总是将项目添加到数组的末尾。相反,您应该对数组进行排序,UITableView 中显示的数据将被排序。

数组具有排序,您可以为其提供比较闭包。您可以制作一个排序方法并将其作为 isOrderedBefore 参数传递给 sort,或者您可以这样做。

stringArray.sort(){ $0 < $1 }

其中 $0$1 是将要比较的第一个和第二个参数。

关于ios - 我如何能够创建一个 tableViewCell 以按字母顺序显示按文本字段添加的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34308451/

相关文章:

ios - SwiftUI:在打开 View 时条件/ObservableObject 更改时更新 View

ios - Rx swift : Two way binding

Java - 最高、最低和平均水平

swift - 你能否将 Swift 泛型约束限制为一组已知类型?

ios - 无法将用户添加到现有的 Parse.com 角色

ios - 如何通过拖动来移动图层?

c# - 数组C#错误Unity3D

arrays - 具有最小数量的相等相邻值的数组改组

仅当从 Xcode 运行时,Swift 包调用/usr/bin/swift 时出现 `Failed to open macho file...Too many levels of symbolic links` 错误

swift - 从 TableViewcell Swift 模拟 tableview 行选择