我有3个单元格的集合视图(CollectionViewController
)(每个单元格都有自己的类)。在第一个单元格(TextCell
)中,我有一个文本字段和一个按钮(nextButton
)。当我按下按钮时,我想检查文本字段是否为空。如果不为空,我想切换到第二个单元格。
CollectionViewController:
let textCell = TextCell()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath)
// TextCell
if indexPath.item == 0 {
let tCell = collectionView.dequeueReusableCell(withReuseIdentifier: textCellId, for: indexPath)
let nextButton = textCell.nextButton
nextButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)
return tCell
}
return cell
}
//Handle Action
@objc func handleNextButton() {
let text = textCell.TextField.text
if text?.isEmpty == false {
scrollToIndex(menuIndex: 1)
} else {
print("Text field is empty.")
}
}
问题是,每次我检查文本字段是否为空时,都会说是空的,尽管不是。
最佳答案
首先-下一行删除,这是不需要的,肯定是错误的!
let textCell = TextCell()
现在,将替换为您的函数:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// TextCell
if indexPath.item == 0 {
let tCell = collectionView.dequeueReusableCell(withReuseIdentifier: textCellId, for: indexPath) as! TextCell
let nextButton = tCell.nextButton
nextButton.addTarget(self, action: #selector(handleNextButton), for: .touchUpInside)
return tCell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath)
return cell
}
和处理程序
//Handle Action
@objc func handleNextButton(sender: UIButton) {
let tCell = sender.superview as! TextCell
let text = tCell.TextField.text
if text?.isEmpty == false {
scrollToIndex(menuIndex: 1)
} else {
print("Text field is empty.")
}
}
关于ios - 检查collectionView中的文本字段是否为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47691378/