如何在表視圖中添加一個目錄樹?
我不確定它是如何呼叫的。是否有一個默認的元素,或者我必須從頭開始制作?
UITableViewController
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return 2;
} else {
return 1;
}
}
- (nonnull UITableViewCell *)tableView: (nonnull UITableView *)tableView
cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
UITableViewCell *cellView = [tableView dequeueReusableCellWithIdentifier:@"cell"/span>]。
if (!cellView) {
cellView = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"cell"】。]
}
return cellView。
}
uj5u.com熱心網友回復:
沒有 "內置樹狀視圖 "型別的UI組件,但你可以通過單元格的.indentationLevel和.indentationWidth屬性來實作。
這是一個非常簡單的例子:
struct IndentDataStruct {
var level: Int =0
var title: String = ""/span>
}
class TreeTableViewController: UITableViewController {
var myData: [IndentDataStruct] = [].
override func viewDidLoad() {
super.viewDidLoad()
var ids: IndentDataStruct!
ids = IndentDataStruct(level: 0, title: "收藏夾")
myData.append(ids)
for i in 1..2 {
ids = IndentDataStruct(level: 1, title: "最愛(i)")
myData.append(ids)
}
ids = IndentDataStruct(level: 0, title: "Bookmarks")
myData.append(ids)
for i in 1..3 {
ids = IndentDataStruct(level: 1, title: "書簽(i)")
myData.append(ids)
}
ids = IndentDataStruct(level: 0, title: "其他")
myData.append(ids)
for i in 1..2 {
ids = IndentDataStruct(level: 1, title: "其他(i)")
myData.append(ids)
for j in 1..2 {
ids = IndentDataStruct(level: 2, title: "其他子(i)-(j)")
myData.append(ids)
}
}
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "defaultCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "defaultCell"/span>, for: indexPath)
讓d = myData[indexPath.row] 。
c.textLabel?.text = d.title
c.indentationLevel = d.level
//只是為了顯示不同的縮進寬度...。
c.indentationWidth = d.level == 2 ? 32 : 16 ?
return c
}
而輸出結果是:
注意,這個例子使用了默認的UITableViewCell類,它自動處理縮進。
如果您使用的是自定義單元格,您需要自行調整。
假設您將單元格的元素限制在單元格的contentView.layoutMarginsGuide(您應該這樣做),您將需要實作:
override func layoutSubviews() {
super.layoutSubviews()
contentView.layoutMargins.left = CGFloat(indentationLevel)* indentationWidth
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/307436.html
標籤:


