indexpath.row 从 1 而不是 0 开始。
我怎样才能摆脱空索引 0?
import UIKit
class ViewController: UITableViewController {
var path: String?
var data: String?
var TableView1 = [String]()
var TableView2 = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.path = NSBundle.mainBundle().pathForResource("textFile", ofType: "txt")
self.data = String(contentsOfFile:path!, encoding: NSUTF8StringEncoding, error: nil)
if var content = (data){
//var line: [String] = content.componentsSeparatedByString("\n")
var chp: [String] = content.componentsSeparatedByString("#")
TableView1 += chp
TableView2 += sec
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableView1.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var Cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
Cell.textLabel?.text = TableView1[indexPath.row]
return Cell
}
}
这是文本文件读取的内容以及它如何在 tableview 上显示的屏幕截图
最佳答案
这种行为是正常的,从componentsSeparatedByString
的文档中看NSString
类:
Discussion.
The substrings in the array appear in the order they did in the receiver. Adjacent occurrences of the separator string produce empty strings in the result. Similarly, if the string begins or ends with the separator, the first or last substring, respectively, is empty. For example, this code fragment:
NSString *list = @"Karin, Carrie, David"; NSArray *listItems = [list componentsSeparatedByString:@", "];
.
produces an array { @"Karin", @"Carrie", @"David"" }.If
list
begins with a comma and space—for example, @", Norman, Stanley, Fletcher"—the array has these contents: { @"", @"Norman", @"Stanley", @"Fletcher" }If
list
has no separators—for example, "Karin"—the array contains the string itself, in this case { @"Karin" }.
您的文本文件以分隔符开头,因此空字符串是数组的第一项。
编辑:
一个解决方案就是删除第一项:
class ViewController: UITableViewController {
var tableData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
if let path = NSBundle.mainBundle().pathForResource("textFile", ofType: "txt"),
data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil) {
tableData = data.componentsSeparatedByString("#")
tableData.removeAtIndex(0)
}
}
}
...
关于ios - UITableView 错误 : indexpath. row is starting from 1 instead of 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32369748/