本文链接
准备
我们需要定义一个UserInfoRow
类型需要遵守Equatable协议
1 2 3 4 5 6 7 8 9 10
| struct User: Equatable { var name: String var email: String var dateOfBirth: Date var pictureUrl: URL? }
func ==(lhs: User, rhs: User) -> Bool { return lhs.name == rhs.name }
|
定义Cell
因为Eureka里Row里其实是一个继承自UITableViewCell
的Cell,先要定义Cell
所有Cell需要用final标记并且遵从CellType协议
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| final class UserInfoCell: Cell<User>, CellType { var userImageView = UIImageView() var nameLabel = UILabel() var emailLabel = UILabel() var dateLabel = UILabel() required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } override func draw(_ rect: CGRect) { userImageView.frame = CGRect(x: rect.midX, y: 0, width: rect.width / 2, height: rect.height) addSubview(userImageView) nameLabel.frame = CGRect(x: 0, y: 0, width: rect.width / 2, height: rect.height / 3) addSubview(nameLabel) emailLabel.frame = CGRect(x: 0, y: rect.height / 3, width: rect.width / 2, height: rect.height / 3) addSubview(emailLabel) dateLabel.frame = CGRect(x: 0, y: rect.height / 3 * 2, width: rect.width / 2, height: rect.height / 3) addSubview(dateLabel) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
|
定义Row
像Cell一样,Row也需要用final标记并且遵从RowType协议
1 2 3 4 5 6 7
| final class UserInfoRow: Row<UserInfoCell>, RowType { required init(tag: String?) { super.init(tag: tag) } }
|
修改Cell的方法
大体模型已经搭建好了,但是数据如何呈现在视图上并没有定义,我们需要重写Cell的setup(实例化单元格后调用)和update(每次刷新单元格时调用)方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| override func setup() { super.setup() selectionStyle = .none
userImageView.contentMode = .scaleAspectFill userImageView.clipsToBounds = true
nameLabel.font = .systemFont(ofSize: 18) emailLabel.font = .systemFont(ofSize: 13.3) dateLabel.font = .systemFont(ofSize: 13.3)
for label in [emailLabel, dateLabel, nameLabel] { label.textColor = .gray }
height = { return 94 }
backgroundColor = UIColor(red:0.984, green:0.988, blue:0.976, alpha:1.00) }
override func update() { super.update()
textLabel?.text = nil detailTextLabel?.text = nil
guard let user = row.value else { return }
if let url = user.pictureUrl, let data = try? Data(contentsOf: url) { userImageView.image = UIImage(data: data) } else { userImageView.image = UIImage(named: "placeholder") }
emailLabel.text = user.email nameLabel.text = user.name let dateFormatter = DateFormatter() dateFormatter.timeStyle = .medium dateFormatter.dateStyle = .medium dateLabel.text = dateFormatter.string(from: user.dateOfBirth)
}
|
显示效果
