微博swift table view的布局
给cell传递模型
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let status = statuses![indexPath.row] // 1.获取cell let cell = tableView.dequeueReusableCell(withIdentifier: StatusTableViewCellIdentifier.cellID(status), for: indexPath) as! StatusTableViewCell // 2.设置数据 cell.status = status // 4.判断是否滚动到了最后一个cell let count = statuses?.count ?? 0 if indexPath.row == (count - 1) { pullupRefreshFlag = true // print("上拉加载更多") loadData() } // 3.返回cell return cell }
设置正文、配图尺寸
var status: Status? { didSet{ // 设置顶部视图 topView.status = status // 设置正文 // contentLabel.text = status?.text contentLabel.attributedText = EmoticonPackage.emoticonString(status?.text ?? "") // 设置配图的尺寸 pictureView.status = status?.retweeted_status != nil ? status?.retweeted_status : status // 1.1根据模型计算配图的尺寸 // 注意: 计算尺寸需要用到模型, 所以必须先传递模型 let size = pictureView.calculateImageSize() // 1.2设置配图的尺寸 pictureWidthCons?.constant = size.width pictureHeightCons?.constant = size.height pictureTopCons?.constant = size.height == 0 ? 0 : 10 } }
添加布局子控件
func setupUI() { // 1.添加子控件 contentView.addSubview(topView) contentView.addSubview(contentLabel) contentView.addSubview(pictureView) contentView.addSubview(footerView) let width = UIScreen.main.bounds.width // 2.布局子控件 topView.xmg_AlignInner(type: XMG_AlignType.topLeft, referView: contentView, size: CGSize(width: width, height: 60)) contentLabel.xmg_AlignVertical(type: XMG_AlignType.bottomLeft, referView: topView, size: nil, offset: CGPoint(x: 10, y: 10)) footerView.xmg_AlignVertical(type: XMG_AlignType.bottomLeft, referView: pictureView, size: CGSize(width: width, height: 44), offset: CGPoint(x: -10, y: 10)) }
获取行高
func rowHeight(_ status: Status) -> CGFloat { // 1.为了能够调用didSet, 计算配图的高度 self.status = status // 2.强制更新界面 self.layoutIfNeeded() // 3.返回底部视图最大的Y值 return footerView.frame.maxY }