簡體   English   中英

如何在 Swift 中獲取 textField 的 IndexPath

[英]How can I get the IndexPath of a textField in Swift

我在我的應用程序中使用分段 tableView,tableView 的每一行都包含一個 textField,當textFieldDidBeginEditing我需要知道該 textField 的 indexPath。 使用標簽只能獲取部分或行,創建UITextField的擴展不允許你添加變量。 我怎樣才能做到這一點?

有辦法做到這一點,但無論如何它都是糟糕的設計,建議您將文本字段委托放在單元格類中。

您可以嘗試使用textField.superview獲取確切的 cell/contentView ,將其轉換為MyTableViewCell ,然后使用tableView.indexPath(for: cell)獲取索引。

不需要標簽來做到這一點。

例子:

var view: UIView = textField
while !view.isKind(of: UITableViewCell.self), let superView = view.superview {
    view = superView
}
if let view = view as? MyTableViewCell {
   //Do sth
}

我喜歡從文本字段走到單元格並詢問表格視圖的索引路徑。

extension UIResponder {
    func next<T:UIResponder>(ofType: T.Type) -> T? {
        let r = self.next
        if let r = r as? T ?? r?.next(ofType: T.self) {
            return r
        } else {
            return nil
        }
    }
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    if let cell = textField.next(ofType: MyCell.self) {
        if let ip = self.tableView.indexPath(for:cell) {
           // whatever
        }
    }
}

cellForRow

var section = indexPath.section + 1
var row = indexPath.row + 1
index = Int("\(section)0\(row)")!

將 textFields 的標簽設置為index

textFieldDidBeginEditing

let indexString = "\(textField.tag)"
let parts = indexString.components(separatedBy: "0")
let row = Int(parts[1])! - 1
let section = Int(parts[0])! - 1

獲取包含文本字段的單元格的 indexPath 的最簡單方法

func getIndexPathFromView(_ sender : UIView) -> IndexPath? {
    let point = sender.convert(CGPoint.zero, to: self.tblView)
    let indexPath = self.tblView.indexPathForRow(at: point)
    return indexPath
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM