我试图在UITableViewController
上进行MVVM集成,但是我一直在努力:
fatal error: unexpectedly found nil while unwrapping an Optional value
上的 super.init(style: style, reuseIdentifier: reuseIdentifier)
。
为什么?我想这与它有关:
cell.menuItemViewModel = SideMenuViewModel(menuItem: item)
因为如果我删除这一行没有错误吗?
在sideMenuController中设置数据源
func setupDatasource() {
let sections = [
SectionModel(model: "menu", items: menuItems)
]
dataSource.configureCell = { (ds, tv, ip, item) in
let cell: MenuCell = tv.dequeueReusableCell(withIdentifier: self.reuseIdentifier, for: ip) as! MenuCell
cell.menuItemViewModel = SideMenuViewModel(menuItem: item)
return cell
}
Observable.just(sections)
.bindTo(tableView.rx.items(dataSource: dataSource))
.addDisposableTo(disposeBag)
}
MenuItem模型
struct MenuItem {
var title: String
var image: Asset
var imageSelected: Asset
var controller: UINavigationController
init(title: String, image: Asset, imageSelected: Asset, controller: UINavigationController) {
self.title = title
self.image = image
self.imageSelected = imageSelected
self.controller = controller
}
}
视图模型
struct SideMenuViewModel {
let title: String
let image: UIImage
let imageSelected: UIImage
init(menuItem: MenuItem) {
self.title = menuItem.title
self.image = UIImage(asset: menuItem.image)
self.imageSelected = UIImage(asset: menuItem.imageSelected)
}
}
MenuCell
class MenuCell: UITableViewCell {
var titleLabel: UILabel!
var iconImageView: UIImageView!
var menuItemViewModel: SideMenuViewModel! {
didSet {
//Set title
self.titleLabel.text = menuItemViewModel.title
//Set image
self.iconImageView.image = menuItemViewModel.image
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupUI() {
//Add titleLabel
self.titleLabel = UILabel()
self.addSubview(self.titleLabel)
//Add iconImageView
self.iconImageView = UIImageView()
self.addSubview(self.iconImageView)
//Customize titleLabel
self.titleLabel.font = FontFamily.Avenir.Regular.font(size: 26)
self.titleLabel.textColor = UIColor.white.withAlphaComponent(0.6)
//Customize iconImageView
self.iconImageView.contentMode = .scaleAspectFit
//Customize cell
self.selectionStyle = .none
self.backgroundColor = UIColor.clear
}
func setupConstraints() {
//titleLabel constraints
self.titleLabel.snp.makeConstraints({ make in
make.left.equalTo(self.iconImageView.snp.right).offset(-20)
make.centerY.equalTo(self)
make.height.equalTo(50)
make.width.equalTo(100)
})
//iconImageView constraints
self.iconImageView.snp.makeConstraints({ make in
make.left.equalTo(80)
make.centerY.equalTo(self)
make.height.equalTo(50)
make.width.equalTo(50)
make.right.equalTo(self.titleLabel.snp.left).offset(20)
})
}
}
答案 0 :(得分:0)
你注册了这个细胞吗?
tableView.register(MenuCell, forCellReuseIdentifier: self.reuseIdentifier)
如果使用Storyboard将类添加到单元格中,则无需注册它,也不应注册。
此外,如果您有错误的reuseIdentifier
,则可能会发生错误。