簡介: 利用范型對同一類的數(shù)據模型統(tǒng)一轉換為同一種視圖模型
定義協(xié)議
//讓數(shù)據模型遵守這個協(xié)議
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協(xié)議的數(shù)據模型疏旨,獲取視圖尺寸方面的數(shù)據
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)
}