ios - 如何在 UITableViewCell 中重用 UIView 的 xib 子类

标签 ios swift uitableview uiview reusability

所以我是一个新手,正在尝试一些可重用性。我有一个名为 SingleButtonFooterView 的类,它是 UIView 的子类,UI 在 .xib 中完成。

现在我想在 UITableViewCell 中使用它。我已经尝试了几乎所有可能的解决方案,但对我没有任何用处。

类(class)代码:

class SingleButtonFooterView: UIView {

@IBOutlet weak var button: Button50!

override init(frame: CGRect) {
    super.init(frame: frame)
    commonInit()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    commonInit()
}

private func commonInit(){
    let view = UINib(nibName: "SingleButtonFooterView", bundle: nil).instantiate(withOwner: self, options: nil).first as! UIView
    view.frame = self.bounds
    self.addSubview(view)
}

override func awakeFromNib() {
    super.awakeFromNib()
    button.backgroundColor = .clear
    button.layer.cornerRadius = 5
    button.layer.masksToBounds = true

    button.titleLabel?.font = UIFont.futura(with: .medium, size: 16)
    button.setTitleColor(.white, for: .normal)
    self.contentMode = .scaleAspectFit
    self.layer.masksToBounds = true
}
}

现在 cellForRowAt:

let cellId = "SingleButtonFooterView"
            var cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

            if cell == nil {
                cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: cellId)
                let subView = SingleButtonFooterView(frame: cell.frame)

                cell.contentView.attachViewWithConstraints(subView)
                let _ = subView.viewLoadedFromNibAttached(name: cellId)
            }

            return cell

在我的 VC 类的 viewDidLoad() 中。

tableView.register(UINib(nibName: "SingleButtonFooterView", bundle: nil), forCellReuseIdentifier: "SingleButtonFooterView")

In short -> I want to use a UIView class (UI done using interface builder -> .xib) in a UITableViewCell

最佳答案

如果我可以建议您做某事,请“照章办事”。

创建自定义单元格和.xib。然后你可以用 UIView 做任何你想做的事(记住你可以创建你自己的类并通过改变这里的类把它放到 xib 中:Where you change class of the UIView

在一个类中有 awakeFromNibInit 它在某种程度上是一种代码味道,因为您使用 .xibcode 创建 View 。

请记住,从 VC 添加 subview 总是有风险的,因为您需要注意回收,这意味着除非您处理这种情况,否则此 subview 可能会保留并且不需要。

记住 prepareForReuse() 来处理细胞的回收。

关于ios - 如何在 UITableViewCell 中重用 UIView 的 xib 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57355146/

相关文章:

iphone - ASIHttprequest 具有一个进度 View 的多个请求

ios - openfire 中需要哪些插件才能进行聊天

ios - 在 UITableViewCell 上实现选择和突出显示动画的正确方法是什么?

ios - 我的 tableView 出现了,但它是空的?怎么修?

c# - UITableViewDelegate 中删除单元格时发生 NSInternalInconsistencyException 错误/Xamarin.iOS

ios - 在 UITableView 的顶部项目重新排序和插入的逻辑是什么

ios - dsymutil 缺少在 iOS 上编译 GNU bash

ios - 动画 UITextView`lik 横幅 "a la"音乐应用程序的库

xcode - 如何在调试时仅打印 Swift 结构的自定义描述,而不打印其他内容?

ios - 无法将 NowPlayingInfo 设置为 nil