简介: 利用范型对同一类的数据模型统一转换为同一种视图模型
定义协议
//让数据模型遵守这个协议
protocol ZYFText {
var title: String?{get}
}
定义视图模型
class ZYFTextViewModel: NSObject {
var title: String?
private var font: UIFont
private var minWidth: CGFloat
private var edgeInsets: UIEdgeInsets
private var stringWidth: CGFloat {
guard let text = title else {
return minWidth
}
return text.sizeWithFont(font).width
}
var viewWidth: CGFloat {
let width = self.stringWidth + self.edgeInsets.left + self.edgeInsets.right
return max(width, minWidth)
}
//利用范性,通过遵守ZYFText协议的数据模型,获取视图尺寸方面的数据
init<T: ZYFText>(item: T, font: UIFont, minWidth: CGFloat, edgeInsets: UIEdgeInsets) {
super.init()
self.title = item.title
self.font = font
self.minWidth = minWidth
self.edgeInsets = edgeInsets
}
}
viewController中的应用
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let minWidth: CGFloat = 60
let font = UIFont.systemFont(ofSize: 15)
let edgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
let item = datasource[indexPath.row]
let textModel = ZYFTextViewModel(item: item, font: font, minWidth: minWidth, edgeInsets: edgeInsets)
return CGSize(width: textModel.viewWidth, height: 40)
}
网友评论