【发布时间】:2017-02-08 09:12:41
【问题描述】:
我在 collectionViewCell 的子视图中添加了一个 UITextField。代码如下:
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)
}
【问题讨论】:
-
您是如何使用按钮操作调用此方法的,希望您在调用按钮操作方法时不要再次初始化该类对象。分享按钮操作代码。
-
刚刚添加。
-
非常明显,它总是会让你空虚。因为您正在初始化单元格并在该类中创建新的文本字段,所以按钮操作会返回新创建的文本字段的值。
-
如果按钮确实存在于同一个单元格中,那么你应该同时调用它的目标。如果没有,那么您需要在按钮操作代码中指定您正在调用哪个单元格的文本字段。分享您的单元格代码,然后我可能会帮助您编写此代码。同时分享您的用户界面。
标签: ios swift xcode uitextfield collectionview