我使用文本字段将文本添加到 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/