我有一个UITextField,我在我的collectionViewCell的子视图中添加了UITextField。下面是代码:在CollectionViewCell中输入UITextField(swift 3 xcode)
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")
}
}
}
我在调用此方法另一个类的按钮,并且在时刻打印文本字段的当前输入(其可以是由于在buttonHandler()功能)。问题是,由于某种原因,textField总是返回为空,我不知道为什么。
编辑:
这是函数按下时(按钮,其功能是在一个单独的类到文本框)的按钮调用:
func testButton() {
let test = ClientCell()
test.handler()
}
SOLUTION:
的问题,我当时我正在想要按下按钮的课程中创建一个我的collectionViewCell的新实例。当函数被调用时,它将是空的。
为了解决这个问题,我使用NSNotificationCenter每次点击该按钮时都发布一个帖子,并且在发布帖子时触发函数的CollectionViewCell类中有观察者。这是代码。
功能按下按钮时调用:
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)
}
你如何使用按钮操作调用此方法,希望你不会初始化该C在调用按钮操作方法时再次调用lass对象。共享按钮操作的代码。 –
现在就添加它。 – rob8989
非常明显,它会一直让你空空如也。因为您正在初始化单元格并在该类中创建新的文本字段,所以按钮操作会返回您新创建的文本字段的值。 –