【问题标题】:Creating a UI Button for a TableViewCell为 TableViewCell 创建 UI 按钮
【发布时间】:2017-01-06 22:12:31
【问题描述】:

我对 Swift 和 Xcode 非常陌生。一旦用户按下返回键,我试图让 UIButton 出现在 tableView 单元格的右侧。现在我只是在一般出现按钮时遇到问题。

据我了解,这里是我的自定义类 TextInputTableViewCell,我认为它应该创建一个按钮:

class TextInputTableViewCell: UITableViewCell {

@IBOutlet weak var textField: UITextField!
var cellButton: UIButton!

func createCellButton()
{
    let image = UIImage(named: "Completed Circle.png")
    cellButton = UIButton(frame: CGRect(x: 340, y: 56, width: 30, height: 30));
    cellButton.setBackgroundImage(image, for: UIControlState.normal)
    addSubview(cellButton)
}

然后在这里我在 ViewController 类中配置单元格的属性:

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{


    let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as! TextInputTableViewCell
    cell.textField.delegate = self
    cell.backgroundColor = UIColor.clear //to get background image loaded
    cell.createCellButton()



    return cell
}

我知道我可能搞砸了。此外,任何关于如何在用户按下回车后出现的提示将不胜感激。我已经设置了 textFieldShouldReturn 函数。

【问题讨论】:

    标签: ios swift uitableview uibutton


    【解决方案1】:

    你为什么不使用故事板制作UIButton 并制作一个 Outlet。然后在cellForRowAtcell.button.isHidden = true cell.button.isUserInteractionEnabled = false (或类似的东西,不确定实际拼写)。然后让你的TextInputTableViewCell符合UITextFieldDelegate

    class TextInputTableViewCell: UITableViewCell, UITextFieldDelegate { ..
    

    单元格内:

     func textFieldShouldReturn(textField: UITextField!) -> Bool {   //delegate method
         self.button.isUserInteractionEnabled = true
         self.button.isHidden = false
         return true
     }
    

    您可能会遇到一些关于单元格可重用性的问题,因此最好创建一些局部变量,例如var userDidEnterText = false,以检查用户是否更改了某些内容

    【讨论】:

    • textFieldShouldReturn 在 TextInputTableViewCell 类中不响应返回键。但它确实在 ViewController 类中。然而在这个类中,当试图引用“self.cellButton...”时会出现编译错误
    • 操作。没注意,试试把cell.textField.delegate = self改成cell.textField.delegate = cell
    • 现在很好用!非常感谢您的帮助!
    • 不要忘记接受,将来会帮助一些人:) 如果您对可重用性有任何疑问,请随时提出。
    【解决方案2】:

    查看createCellButton() 正文,我可以看出xy 的值可能是问题的根源。我认为按钮是从单元格框架中创建的。尝试使用以下参数:

    cellButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      相关资源
      最近更新 更多