我创建了一个带有自定义 collectionViewCell 的 nib 文件并附加到 viewController
class CustomCollectionView: UICollectionViewCell{}
现在我必须使用 tableView 中的确切单元格。我创建了一个新的 nib 文件和 viewController
class CustomTableView: UITableViewCell{}
并且我把CustomCollectionView
的洞代码复制到上面了。一切正常,但我认为将 CustomCollectionView
的完整代码复制到 CustomTableView
并使用完全相同的 nib 文件但带有 tableViewCell
而不是 collectionViewCell
。有什么办法可以优化我所做的吗?
最佳答案
正如您在 suhit 的回答中的评论中所说,您可以通过在 CollectionViewCell
和 TableViewCell
子类中使用公共(public) View 来实现这一点。您不需要 ViewController,因为它会增加额外的开销。一个简单的 UIView 就足够了。一些代码来说明我的意思:
class CustomTableViewCell: UITableViewCell {
var customView: CustomView!
func awakeFromNib() {
super.awakeFromNib()
customView = CustomView()
customView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(customView)
customView.fillSuperview()
}
}
class CustomCollectionViewCell: UICollectionViewCell {
var customView: CustomView!
func awakeFromNib() {
super.awakeFromNib()
customView = CustomView()
customView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(customView)
customView.fillSuperview()
}
}
extension UIView {
func fillSuperview() {
guard let superview = superview else {
return print("no superview")
}
topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
rightAnchor.constraint(equalTo: contentVisuperviewew.rightAnchor).isActive = true
}
}
CustomView
类的示例实现:
class CustomView: UIView {
func initialize() {
//...
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
}
如果您希望在 xib 中创建您的自定义 View ,这也很好,但有点棘手。这超出了问题的范围,但我将留下一个链接 here以防万一。
关于ios - 在 collectionViewCell 和 tableViewCell 中使用相同的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46023853/