![](/img/trans.png)
[英]How can I get the indexPath of a UICollectionViewCell and save it
[英]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.