ios - 快速将文本字段添加到 UITableViewCell

标签 ios swift uitableview uitextfield

我正在尝试在单击按钮时动态添加文本字段。

我认为最简单的方法是拥有一个初始表格 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/

相关文章:

ios - 显示 GTMSessionFetcher 警告的 Swift-Firebase iOS SDK

ios - 在 iPhone 上的一个 UIWebView 中显示多个 PPT

iOS + swift 2 : Dynamic height in UITableViewCell doesn't work with an empty view

ios - 打开设置应用程序

swift - 如何使用 UICollectionViewCompositionalLayout 创建像图像这样的 Collection View

ios - 通过自定义 URL 更改 iOS 中的应用程序图标

SwiftUI - 如何使用文本字段和 .onchange 更新结构中的项目

ios - 在 Swift 中,从 JSON 加载的 tableView 数据仅在 80% 的时间内加载

ios - 我怎样才能在 Swift 5.1 (Xcode 11 Playground) 中为可选项实现泛型和非泛型函数签名的重载?

ios - 找不到 GMSMarker 的协议(protocol)声明