Swift xib以编程方式转换为视图
我需要使用自定义视图,而不是使用xib文件创建的视图 如何转换和使用nib/xib文件以编程方式查看Swift xib以编程方式转换为视图,swift,dynamic,Swift,Dynamic,我需要使用自定义视图,而不是使用xib文件创建的视图 如何转换和使用nib/xib文件以编程方式查看 class CustomCell: UITableViewCell { var item: ViewModelItem? { didSet { titleLabel?.text = item?.title } } override func awakeFromNib() { super.awake
class CustomCell: UITableViewCell {
var item: ViewModelItem? {
didSet {
titleLabel?.text = item?.title
}
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
}
@IBOutlet weak var titleLabel: UILabel?
static var nib:UINib {
return UINib(nibName: identifier, bundle: nil)
}
static var identifier: String {
return String(describing: self)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
accessoryType = selected ? .checkmark : .none
}
}
我添加了它而不是xib。我该怎么寄这个
我希望通过编程方式添加和控制xib文件。
我希望通过编程方式添加和控制xib文件
class CustomCellView: UIView {
convenience init(frame: CGRect,checkboxTag:Int?) {
self.init(frame: frame)
self.addCustomView(checkboxTag: checkboxTag)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addCustomView(checkboxTag : Int?) {
var checkbox: UIButton = ClickingCheckbox()
if((checkboxTag) != nil)
{
checkbox.tag = checkboxTag!
}
self.addSubview(checkbox)
}
}
class ClickingCheckbox: UIButton {
convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
self.setImage(UIImage(named: "unfilled.png"), for: UIControlState.selected)
self.setImage(UIImage(named: "filled.png"), for: UIControlState.normal)
self.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
}
@objc private func buttonTapped() {
self.isSelected = !self.isSelected
}
}
当您使用来自Nib的视图时,它调用
AwakeFromNib()
方法,来自代码的自定义视图使用Init()方法。
要将Xib转换为编程代码,您需要在
Init()
方法中设置所有UI,并将所有初始配置方法从AwakeFromNib()
移动到Init()清楚地解释问题陈述。我不完全理解,我可以问一个简单的代码示例吗?