Swift 教程之TableView使用04卡片式Cell
2019-05-06 本文已影响5人
iCloudEnd
Swift 教程之TableView使用03自定义Cell
之前系列课程
效果图
Jietu20190506-081028@2x.jpg1. 修改cell高度
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 240
}
2. 配置一下数据
import UIKit
struct SectionData{
var open:Bool
var data:[CellData]
}
struct CellData {
var title: String
var featureImage: UIImage
var info: String
}
3. 配置一下图片视图
fileprivate var featureImage: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.contentMode = .scaleAspectFill
iv.layer.masksToBounds = true
iv.layer.cornerRadius = 2
return iv
}()
我们给图片设置个圆角, iv.layer.cornerRadius = 2,这样可以让图片显得不会生硬。
4. 配置一下图片标题
fileprivate var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
label.textColor = .black
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
我们设置图片标题为黑色,适当加重字体,显得字体突出
5. 配置一下图片简介
fileprivate var infoText:UITextView = {
let infoText = UITextView()
infoText.font = UIFont.systemFont(ofSize: 12, weight: .light)
infoText.textColor = .black
infoText.isEditable = false
infoText.translatesAutoresizingMaskIntoConstraints = false
return infoText
}()
图片简介要和标题有个区分,我们将他的字体调小,并让字体显得更轻快一些。
6. 配置一下图片、标题和简介的位置关系
fileprivate func setupConstraints(){
contentView.addSubview(featureImage)
contentView.addSubview(titleLabel)
contentView.addSubview(infoText)
featureImage.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8).isActive = true
featureImage.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8).isActive = true
featureImage.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8).isActive = true
featureImage.heightAnchor.constraint(equalToConstant: 140).isActive = true
titleLabel.topAnchor.constraint(equalTo: featureImage.bottomAnchor, constant: 8).isActive = true
titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8).isActive = true
titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8).isActive = true
infoText.topAnchor.constraint(equalTo: titleLabel.bottomAnchor).isActive = true
infoText.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8).isActive = true
infoText.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8).isActive = true
infoText.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8).isActive = true
}
7. 配置一下Cell,突出一下卡片风格
override func layoutSubviews() {
super.layoutSubviews()
contentView.frame = contentView.frame.inset(by: UIEdgeInsets(top: 10, left: 30, bottom: 10, right: 30))
}