一、前言
- 我們在寫列表的時候,經(jīng)常出現(xiàn)每一個 Cell 高度不一樣的情況,但是 iOS 這邊是在是太不智能了
- 比起隔壁
android的RecyclerView,人家可以自動更具每一項高度,來進行伸縮變化,iOS的列表控件UITableView竟然都不能直接自適應(yīng)列表高度
二、效果
- 其實具體的實現(xiàn)并不難,只是沒學(xué)過的人肯定搞不出來,開始前這里可以先看下效果
- 大致就是
UITableView會自動計算每一個cell的高度,伸縮變換后顯示出來,網(wǎng)上有很多類似的帖子,但是大都紙上談兵,沒圖沒代碼地講不清楚,而且還都是n年前的文章 -
那么開始前。效果圖這里效果圖如下:
image
三、使用與實現(xiàn)
- 就以上圖為例,我?guī)Т蠹疫呏v解邊實現(xiàn)上圖中的例子,這樣一來成功運行的時候,大家就也都會了
3.1 實現(xiàn)數(shù)據(jù)提供者 - ContentProvider
- 實現(xiàn)一個數(shù)據(jù)提供者 - ContentProvider ,用于模擬從網(wǎng)絡(luò)上拉去數(shù)據(jù)的情況
class ContentProvider {
static let datas = ["對我個人而言,美麗的沙灘不僅僅是一個重大的事件,還可能會改變我的人生。",
"美麗的沙灘因何而發(fā)生? 我認為, 那么, 查爾斯·史考伯在不經(jīng)意間這樣說過,一個人幾乎可以在任何他懷有無限熱忱的事情上成功。",
"對我個人而言,美麗的沙灘不僅僅是一個重大的事件,還可能會改變我的人生。 帶著這些問題,我們來審視一下美麗的沙灘。 美麗的沙灘,發(fā)生了會如何,不發(fā)生又會如何。 帶著這些問題,我們來審視一下美麗的沙灘。 既然如何, 我認為, 而這些并不是完全重要,更加重要的問題是, 這樣看來, 帶著這些問題,我們來審視一下美麗的沙灘。",
"我們都知道,只要有意義,那么就必須慎重考慮。",
"對我個人而言,美麗的沙灘不僅僅是一個重大的事件,還可能會改變我的人生。",
"美麗的沙灘因何而發(fā)生? 我認為, 那么, 查爾斯·史考伯在不經(jīng)意間這樣說過,一個人幾乎可以在任何他懷有無限熱忱的事情上成功。",
"莎士比亞說過一句富有哲理的話,人的一生是短的,但如果卑劣地過這一生,就太長了。這似乎解答了我的疑惑。 帶著這些問題,我們來審視一下美麗的沙灘。 ",
"一般來說, 既然如此, 這樣看來, 我們都知道,只要有意義,那么就必須慎重考慮。 每個人都不得不面對這些問題。 在面對這種問題時, 了解清楚美麗的沙灘到底是一種怎么樣的存在,是解決一切問題的關(guān)鍵。",
"我們都知道,只要有意義,那么就必須慎重考慮。"]
static let imgs = ["paperplane.fill","square.and.arrow.down","paperplane.fill","bell","square.and.arrow.down","bell","paperplane.fill","bell","square.and.arrow.down"]
}
這里節(jié)約時間,就不做異步拉取的處理了,后續(xù)文章我會擠時間,專門搞一篇
UITableView異步請求加觀察者模式的文章來給大家分享
3.2 編寫列表 item - UITableViewCell
- 要讓
cell隨自身內(nèi)容大小而變化高度,只需要注意三點即可 - 首先是,
addSubView必須是添加到contentView上,而非簡單的self - 其次是,內(nèi)部組件必須設(shè)置
translatesAutoresizingMaskIntoConstraints屬性為true - 最后是,這個
cell不能通過簡單的frame設(shè)置大小,而是需要通過NSLayoutConstraint來動態(tài)給定 - 首先這里我先提供下最終實現(xiàn)的代碼再逐個給大家分析:
import Foundation
import UIKit
class MemberCell: UITableViewCell {
lazy var contentLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(label)
label.numberOfLines = 0
return label
}()
lazy var userImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(imageView)
imageView.image = UIImage(systemName: "Camera")
return imageView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupConstraint()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupConstraint() {
userImageView.accessibilityIdentifier = "userImageView"
contentLabel.accessibilityIdentifier = "profileImageView"
contentView.accessibilityIdentifier = "profileContentView"
NSLayoutConstraint.activate([
contentLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
contentLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10),
contentLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10),
userImageView.topAnchor.constraint(equalTo: contentLabel.bottomAnchor, constant: 10),
userImageView.widthAnchor.constraint(equalToConstant: 25),
userImageView.heightAnchor.constraint(equalToConstant: 25),
userImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10),
userImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
])
}
}
3.2.1 子控件實現(xiàn)
- 為了提高代碼可讀性,這里建議大家使用懶加載的形式
- 我們注意到,子控件的
view是需要添加到cell的contentView上的,而非直接添加到 self 上 - 另一點就是之前說的,需要把
view的translatesAutoresizingMaskIntoConstraints屬性設(shè)置為false - 拿代碼 + 注釋舉個例子:
lazy var contentLabel: UILabel = {
let label = UILabel()
// translatesAutoresizingMaskIntoConstraints 設(shè)為 false
label.translatesAutoresizingMaskIntoConstraints = false
// 添加到 contentView
self.contentView.addSubview(label)
label.numberOfLines = 0
return label
}()
3.2.2 計算子控件以及 cell 大小
- 這里我們就不能再采用上古時代設(shè)定
frame的方法而是通過NSLayoutConstraint.activate([...])中設(shè)定子控件各邊與 cell 各邊的關(guān)系來指定 - 另外一點就是,對于每個子
view以及我們cell的conteentView我們都需要設(shè)定它們的accessibilityIdentifier,其內(nèi)容直接寫該view的名字就行,只要不重名就行,沒有太多的要求 - 給大家舉個栗子 ?? :
func setupConstraint() {
//
userImageView.accessibilityIdentifier = "userImageView"
contentLabel.accessibilityIdentifier = "profileImageView"
contentView.accessibilityIdentifier = "profileContentView"
// 設(shè)定子布局各邊與 cell 的關(guān)系
NSLayoutConstraint.activate([
contentLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
contentLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10),
contentLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10),
userImageView.topAnchor.constraint(equalTo: contentLabel.bottomAnchor, constant: 10),
userImageView.widthAnchor.constraint(equalToConstant: 25),
userImageView.heightAnchor.constraint(equalToConstant: 25),
userImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10),
userImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10),
])
}
其中子
view的大小,我們同樣可以在activate([...])中,通過widthAnchor & heightAnchor強制來設(shè)定
3.3 列表界面 - UITableViewController
- 相比于 cell 中的注意點,對于
UItableView本身需要注意的地方并不多 - 相比于普通
UItableView的使用,這里要添加translatesAutoresizingMaskIntoConstraints的設(shè)置 - 同時通過
NSLayoutConstraint.activate(...)設(shè)置設(shè)置tableView之于ViewController大小
import Foundation
import UIKit
class LandscapeListViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
config()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NSLayoutConstraint.activate(tableView.edgeConstraints(top: 80, left: 0, bottom: 0, right: 0))
}
func config() {
tableView.delegate = self
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableView.automaticDimension
tableView.register(MemberCell.self, forCellReuseIdentifier: "MemberCell")
}
}
extension LandscapeListViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return max(ContentProvider.datas.count, ContentProvider.imgs.count)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MemberCell", for: indexPath) as! MemberCell
cell.contentLabel.text = ContentProvider.datas[indexPath.row]
cell.userImageView.image = UIImage(systemName: ContentProvider.imgs[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
3.3.1 自動標注尺寸
- 首先我們需要設(shè)置
UITableView的高度計算方案為自動標注尺寸,也就是automaticDimension - 其次我們同樣需要標注
tableview的translatesAutoresizingMaskIntoConstraints為false
func config() {
tableView.delegate = self
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableView.automaticDimension
tableView.register(MemberCell.self, forCellReuseIdentifier: "MemberCell")
}
3.3.2 設(shè)定大小
- 更
TableViewCell一樣,對于viewController中的tableView,我們也需要設(shè)定它們的大小關(guān)系 - 為了方便起見,我才用了網(wǎng)上的一套設(shè)定方案:
extension UIView {
/// 設(shè)定 view 與其父 view 各邊之間的關(guān)系
public func edgeConstraints(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) -> [NSLayoutConstraint] {
return [
self.leftAnchor.constraint(equalTo: self.superview!.leftAnchor, constant: left),
self.rightAnchor.constraint(equalTo: self.superview!.rightAnchor, constant: -right),
self.topAnchor.constraint(equalTo: self.superview!.topAnchor, constant: top),
self.bottomAnchor.constraint(equalTo: self.superview!.bottomAnchor, constant: -bottom)
]
}
}
- 這樣一來,帶代碼里我們只要通過
view.edgeConstraints(...)就可以快速設(shè)定子view與其superview之間的關(guān)系:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// 調(diào)用封裝的方法:edgeConstraints()
NSLayoutConstraint.activate(tableView.edgeConstraints(top: 80, left: 0, bottom: 0, right: 0))
}
總結(jié)
- 我在
GitHub新建了一個倉庫,正在為大家整理、分享我的iOS學(xué)習(xí)筆記,歡迎大家star支持:https://github.com/Knowledge-Precipitation-Tribe/ios_notes - 如果大家有更好的方案,歡迎在評論區(qū)分享代碼,我會更新到本文中 ??
- 同時歡迎大家點贊或者關(guān)注支持,因為這是我持續(xù)輸出的最大動力~