在原型单元格中填充文本字段
Populating text field in prototype cell
目前,我有一些在 Storyboard 中创建的自定义单元格原型,其中嵌入了文本字段。要访问这些文本字段,我在 cellForRowAtIndexPath:
中使用 nameTextField = cell.viewWithTag:(1)
。但是 viewDidLoad:
和 viewWillAppear:
方法在 cellForRowAtIndexPath
之前被调用,所以那时 nameTextField
是 nil
。要在屏幕上显示 table 视图时填充文本字段,我使用 viewDidAppear:
,但它会导致明显的延迟。此外,当我上下滚动 table 视图时,cellForRowAtIndexPath:
被一次又一次地调用,重置已在文本字段中输入的数据。
是否有更有效的方法来在视图显示之前用数据填充自定义单元格原型中嵌入的文本字段,并防止在每次 cellForRowAtIndexPath:
调用中重置输入的数据?
在 viewDidLoad 中尝试 运行 类似 self.tableView.reloadData 的东西,然后再执行此行 "nameTextField = cell.viewWithTag:(1)".
我不确定我是否完全理解你想要做什么,但单元格通常是在 cellForRowAtIndexPath:
方法中配置的,而不是在 viewDidLoad
中。您还可以尝试将文本字段连接到自定义单元格 class 上的插座。然后你可以这样做:
// in view controller
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
as! CustomCell
let object = myDataSource[indexPath.row]
cell.textField.text = object.description
cell.shouldBecomeFirstResponder = indexPath.row == 0
return cell
}
// then in the cell
class CustomCell: UITableViewCell {
@IBOutlet weak var textField: UITextField!
var shouldBecomeFirstResponder: Bool = false
override func awakeFromNib() {
if shouldBecomeFirstResponder {
textField.becomeFirstResponder()
}
}
}
然后当用户在文本字段中输入文本时,更新您的数据源就有意义了。
我猜您正在创建个人资料屏幕(或带有许多文本字段以从用户那里获取输入数据的东西)。我对吗?
如果我是对的,您可以使用静态 tableView(当您有几个文本字段时)
希望这对您有所帮助。
目前,我有一些在 Storyboard 中创建的自定义单元格原型,其中嵌入了文本字段。要访问这些文本字段,我在 cellForRowAtIndexPath:
中使用 nameTextField = cell.viewWithTag:(1)
。但是 viewDidLoad:
和 viewWillAppear:
方法在 cellForRowAtIndexPath
之前被调用,所以那时 nameTextField
是 nil
。要在屏幕上显示 table 视图时填充文本字段,我使用 viewDidAppear:
,但它会导致明显的延迟。此外,当我上下滚动 table 视图时,cellForRowAtIndexPath:
被一次又一次地调用,重置已在文本字段中输入的数据。
是否有更有效的方法来在视图显示之前用数据填充自定义单元格原型中嵌入的文本字段,并防止在每次 cellForRowAtIndexPath:
调用中重置输入的数据?
在 viewDidLoad 中尝试 运行 类似 self.tableView.reloadData 的东西,然后再执行此行 "nameTextField = cell.viewWithTag:(1)".
我不确定我是否完全理解你想要做什么,但单元格通常是在 cellForRowAtIndexPath:
方法中配置的,而不是在 viewDidLoad
中。您还可以尝试将文本字段连接到自定义单元格 class 上的插座。然后你可以这样做:
// in view controller
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
as! CustomCell
let object = myDataSource[indexPath.row]
cell.textField.text = object.description
cell.shouldBecomeFirstResponder = indexPath.row == 0
return cell
}
// then in the cell
class CustomCell: UITableViewCell {
@IBOutlet weak var textField: UITextField!
var shouldBecomeFirstResponder: Bool = false
override func awakeFromNib() {
if shouldBecomeFirstResponder {
textField.becomeFirstResponder()
}
}
}
然后当用户在文本字段中输入文本时,更新您的数据源就有意义了。
我猜您正在创建个人资料屏幕(或带有许多文本字段以从用户那里获取输入数据的东西)。我对吗?
如果我是对的,您可以使用静态 tableView(当您有几个文本字段时)
希望这对您有所帮助。