所以我是一个新手,正在尝试一些可重用性。我有一个名为 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 中:
在一个类中有 awakeFromNib
和 Init
它在某种程度上是一种代码味道,因为您使用 .xib
或 code
创建 View 。
请记住,从 VC 添加 subview 总是有风险的,因为您需要注意回收,这意味着除非您处理这种情况,否则此 subview 可能会保留并且不需要。
记住 prepareForReuse()
来处理细胞的回收。
关于ios - 如何在 UITableViewCell 中重用 UIView 的 xib 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57355146/