繁体   English   中英

在CollectionViewCell中输入UITextField(swift 3 xcode)

[英]Input of UITextField in CollectionViewCell (swift 3 xcode)

我有一个UITextField,它已添加到collectionViewCell的子视图中。 这是代码:

class ClientCell: UICollectionViewCell {

var width: CGFloat!
var height: CGFloat!

var textField: UITextField!

override init(frame: CGRect) {
    super.init(frame: frame)
    width = bounds.width
    height = bounds.height
    setupViews()
}

func basicTextField(placeHolderString: String) -> UITextField {
    let textField = UITextField()
    textField.font = UIFont.boldSystemFont(ofSize: 12)
    textField.attributedPlaceholder = NSAttributedString(string: placeHolderString, attributes:[NSForegroundColorAttributeName: UIColor.lightGray, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12)])
    textField.backgroundColor = UIColor.white
    textField.translatesAutoresizingMaskIntoConstraints = false
    return textField
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func setupViews() {
    backgroundColor = UIColor.white
    layer.addBorder(edge: UIRectEdge.bottom, color: .black, thickness: 0.5)

    textField = basicTextField(placeHolderString: "name")

    addSubview(textField)

}

func buttonHandler() {

    if let textFieldInput = textField.text {
        print (textFieldInput)
    } else {
        print("Nothing in textField")
    }
}

}

我在另一个类中有一个调用此方法的按钮,此刻打印出textField的当前输入(可能是因为在buttonHandler()函数中)。 问题是,由于某些原因,textField总是返回为空,但我不确定为什么。

编辑:

这是按钮在按下时调用的函数(按钮及其功能位于textField的单独类中):

func testButton() {
    let test = ClientCell()
    test.handler()
}

解:

我遇到的问题是,我在要按下按钮的类中创建了collectionViewCell的新实例。 调用该函数时将为空。

为了解决此问题,我每次单击按钮时都使用NSNotificationCenter进行发布,并且在发布发布时触发了函数的CollectionViewCell类中的观察者。 这是代码。

按下按钮时调用的函数:

func saveData() {
    NotificationCenter.default.post(name: NSNotification.Name("saveProject"), object: nil)
}

collectionViewCell的viewDidLoad内部的代码:

class ClientCell: UICollectionViewCell {

override init(frame: CGRect) {
    super.init(frame: frame)
    NotificationCenter.default.addObserver(self, selector: #selector(handler), name: NSNotification.Name("saveProject"), object: nil)
}

最后,该类中的观察者调用的函数

func handler() {

    print(textField.text)
}

我将您的代码放在我的Playgroud项目中。 这是工作。 因此,我认为您的问题并非来自此类。 这是操场上的代码:

func buttonHandler() {
    print(self.textField.text)
    if let textFieldInput = self.textField.text {
        print (textFieldInput)
    } else {
        print("Nothing in textField")
    }
}

let cell = ClientCell(frame: CGRect(x: 0, y: 0, width: 200, height: 50 ))
cell.buttonHandler()

在控制台中,我有这个

可选的(””)

用一个空的ligne。 (由于此打印“ print(textFieldInput)”)

否则,您的代码中需要修复一些问题:

1)在“ basicTextField”函数中:您需要指定textField的框架

let textField = UITextField(frame: YOUR_DESIRED_FRAME)

2)在“ setupViews”功能中,您应该在Cell的内容视图中添加textField:

contentView.addSubview(textField)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM