繁体   English   中英

UITABLEVIEWCELL 的扩展无法在 swift 中工作

[英]Extension for UITABLEVIEWCELL not working in swift

我创建了扩展:

 public extension UITableViewCell {
        /// Generated cell identifier derived from class name
        static func cellIdentifier() -> String {
            return String(describing: self)
        }
      
        var indexPath:IndexPath?{
               return tableView?.indexPath(for: self)
        }
      
        var tableView: UITableView? {
               var view = superview
               while let v = view, v.isKind(of: UITableView.self) == false {
                   view = v.superview
               }
               return view as? UITableView
        }
    }

我正在尝试在 uitableviewcell 类中使用扩展:

func setup(viewModel: ViewModelClass) {       
        if indexPath != nil {
            print("indexpath") 
        }else {
            print("nil")  // But it always gives nill.
        }
}

我想在 uitableviewcell 中获取索引的部分和行。

看看这个扩展。 我在项目中使用它来获取 UITableViewCell 子类中的 indexPath 和 tableView 并且它工作得很好。

private extension UIResponder {
    func next<T: UIResponder>(_ type: T.Type) -> T? {
        return next as? T ?? next?.next(type)
    }
}

extension UITableViewCell {

    var tableView: UITableView? {
        return next(UITableView.self)
    }

    var indexPath: IndexPath? {
        return tableView?.indexPath(for: self)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM