创建可重用视图时如何分配TextField委托和方法

时间:2019-01-31 20:35:50

标签: swift model-view-controller delegates

我正在尝试在我的应用程序中创建可重用的UI组件,此特定组件包含一个UITextFeild。我已经成功在视图中设置了文本字段,并且显示效果完美,但是...文本字段委托设置不起作用。

我尝试像这样从创建的对象引用文本字段

let sessionNameCell = ReusableComponents().createTextFieldCell()
sessionNameCell.textField.delegate = self

但是不能从控制器引用文本字段。

我还尝试过在创建视图的函数内部以多种方式设置委托:

textField.delegate = self

textField.delegate = ViewController()

最后一个崩溃了应用程序,据我了解,创建对象实例不是合适的解决方案

完整代码是...

视图控制器

class HostSessionSetupController : UITableViewController, UITextFieldDelegate {

private var sessionNameCell: UITableViewCell = ReusableComponents().createEditableTableRow(title: "Session Name", placeholder: "e.g. Marks birthday")

override func viewDidLoad() {
    super.viewDidLoad()

    sessionNameCell.textField.delegate = self

}

// The delegate method i need to run
func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    if let input = textField.text {
        if input != ""{
            self.title = "Setup " + input
        } else {
            self.title = "Setup Session"
        }
    }
}

查看功能

func createTableRow(title: String, accessoryType: UITableViewCell.AccessoryType = .none) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.backgroundColor = .backgroundDarkBlack
    cell.textLabel?.textColor = .white
    cell.textLabel?.text = title
    cell.selectionStyle = .none
    cell.accessoryType = accessoryType

    return cell
}

func createEditableTableRow(title: String, placeholder: String) -> UITableViewCell{

    let cell = createTableRow(title: title)
    let textField = UITextField(frame: CGRect(x:  40, y: 0, width: cell.frame.width, height: cell.frame.height))

    textField.textColor = .white
    textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: UIColor.init(white: 1, alpha: 0.5)])
    textField.keyboardAppearance = .dark
    textField.returnKeyType = .default
    textField.textAlignment = .right

    cell.addSubview(textField)

    return cell

}

我要从所有这些功能中获得的唯一功能是在键盘返回时隐藏键盘! D:

感谢所有帮助!

1 个答案:

答案 0 :(得分:0)

创建单元格时,需要设置TextField的委托

相关问题