我正在尝试在单击按钮时动态添加文本字段。
我认为最简单的方法是拥有一个初始表格 View ,然后动态添加包含文本字段的新单元格。
但是,当我添加一个新单元格时 - 文本字段在下方显示 2 个单元格 - 我无法弄清楚我做错了什么..
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("in delegte table view")
return createTableRow()
}
func createTableRow() -> UITableViewCell{
let cell:UITableViewCell = self.extraGuestsTable.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
cell.textLabel?.text = "some text"
let tf = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 20))
tf.placeholder = "Enter text here"
tf.font = UIFont.systemFont(ofSize: 15)
//cell.contentView.addSubview(tf)
cell.addSubview(tf)
return cell
}
如何使文本字段出现在正确的表格 View 单元格中? 谢谢
编辑
谢谢大家 - 正如一些人指出的那样,问题在于 y 位置设置为 100 - 因此显示在单元格下方。 应该是:
let tf = UITextField(frame: CGRect(x: 20, y: 0, width: 300, height: 20))
最佳答案
文本字段框架应与单元格大小一致并检查您的数据源
使用
cell.contentView.addSubview(tf)
代替 cell.addSubview(tf)
默认高度是44,如果你想要更多那么实现相应的委托(delegate)
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
最后添加代码
class customCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
然后更改您的代码:
let cell: customCell = self.extraGuestsTable.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as customCell!
let tf = UITextField(frame: CGRect(x: 20, y: 0, width: 300, height: 20))
tf.placeholder = "Enter text here"
tf.font = UIFont.systemFont(ofSize: 15)
//cell.contentView.addSubview(tf)
cell.addSubview(tf)
return cell
关于ios - 快速将文本字段添加到 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43341286/