[英]Check if text field in collectionView is empty
我有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:
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.")
}
}
要確定UICollectionViewCell
內的UITextField
是否為空,單擊按鈕時需要傳遞索引位置。 要傳遞索引位置,您可以使用標簽。 通過使用標簽,您可以獲得單擊的索引位置。 獲取位置后,可以使用cellForItemAtIndexPath從當前索引位置訪問元素。 您可以使用獲取的單元格引用找到特定的索引位置UITextField為空或不為空
在您的cellForItemAt
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item == 0{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YOUR_CELL_IDENTIFIER", for: indexPath) as! YOUR_UICOLLECTIONVIEW_CELL
cell.nextBtn.tag = indexPath.item
cell.nextBtn.addTarget(self, action: #selector(handleNextButton(_:)), for: .touchUpInside)
return cell
} else {
///use your other cells here
}
}
在您的ViewController中
func handleNextButton(_ sender:UIButton){
let indexPath = IndexPath(item:sender.tag,section:0)
let cell = YOUR_COLLECTIONVIEW.cellForItem(at: indexPath) as! YOUR_UICOLLECTIONVIEW_CELL
if cell.txtFld.text == "" {
print("TextField is empty")
} else {
print("TextField not empty")
}
}
希望這個能對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.