ios - 在 collectionViewCell 和 tableViewCell 中使用相同的 View

标签 ios swift uitableview uicollectionview

我创建了一个带有自定义 collectionViewCell 的 nib 文件并附加到 viewController

class CustomCollectionView: UICollectionViewCell{}

现在我必须使用 tableView 中的确切单元格。我创建了一个新的 nib 文件和 viewController

class CustomTableView: UITableViewCell{}

并且我把CustomCollectionView的洞代码复制到上面了。一切正常,但我认为将 CustomCollectionView 的完整代码复制到 CustomTableView 并使用完全相同的 nib 文件但带有 tableViewCell 而不是 collectionViewCell 。有什么办法可以优化我所做的吗?

最佳答案

正如您在 suhit 的回答中的评论中所说,您可以通过在 CollectionViewCellTableViewCell 子类中使用公共(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/

相关文章:

iphone - 使用 CoreData 创建静态库时出现问题 - 无法使用 nil 模型创建 NSPersistentStoreCoordinator

ios - 颜色作为 slider 位置的函数,用于设置颜色

ios - 仅当在 Swift 中获取所有记录时,如何才能将从 json 异步获取的记录添加到数组中?

ios - 当参与者快速加入时,不会调用 ooVooAVChatDelegate

objective-c - 滚动时 UITableView subview 出现在错误的部分?

swift - 文件夹的 macOS 安全范围 URL 书签

ios - Swift 函数/方法中的 "_"字符

ios - UITableView 委托(delegate)方法未在 swift 3 中调用

ios - 在 Xcode 类型 "ViewController"中获取错误不符合协议(protocol)“UITableViewDataSource”

ios - 如何在一个 UITableView 中制作多个列表? iOS swift