如何在 UITableViewCell 中重用 UIView 的 xib 子类 [英] How to Re-use an xib subclass of UIView in UITableViewCell
问题描述
所以我是一个新手,正在尝试一些可重用性.我有一个名为 SingleButtonFooterView
的类,它是 UIView
的子类,UI 在 .xib
中完成.
So I'm a newbie and trying some reusability. I've a class called SingleButtonFooterView
which subclasses UIView
and UI is done in an .xib
.
现在我想在 UITableViewCell
中使用它.我已经尝试了几乎所有可能的解决方案,但对我没有任何作用.
Now I want to use this in a UITableViewCell
. I've tried almost all possible solutions nothing is working for me.
课程代码:
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()
中.
and in viewDidLoad()
of my VC class.
tableView.register(UINib(nibName: "SingleButtonFooterView", bundle: nil), forCellReuseIdentifier: "SingleButtonFooterView")
简而言之-> 我想在 UITableViewCell 中使用 UIView 类(使用界面构建器完成的 UI -> .xib)
推荐答案
如果我能给你建议的话,就照着书"去做.
If I can suggest you something just do it "by the book".
创建自定义单元格和 .xib
.然后你可以用 UIView
s 做任何你想做的事情(记住你可以创建自己的类,并通过在此处更改类将其放入 xib:
Create a custom cell and .xib
. Then you can do whatever you want with the UIView
s (remember that you can create your own class and put it into xib by changing the class here:
在一个类中使用 awakeFromNib
和 Init
它在某种程度上是一种代码气味,因为您使用 .xib
或 code
创建视图.
Having awakeFromNib
and Init
in one class it's somehow a code smell because either you use .xib
or code
to create a view.
请记住,从 VC 添加子视图总是有风险的,因为您需要注意回收,这意味着除非您处理这种情况,否则该子视图可能会保留并且不需要.
Remember that adding subviews from the VC it's always risky because you need to take care of recycle, what means that this subview may stay and be not wanted unless you handle this situation.
记住 prepareForReuse()
来处理细胞的回收.
Remember about prepareForReuse()
to handle cells' recycle.
这篇关于如何在 UITableViewCell 中重用 UIView 的 xib 子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!