gpt4 book ai didi

ios - 以编程方式创建的 UITableViewCell 仅使用 AutoLayout 显示其第一个 subview

转载 作者:行者123 更新时间:2023-11-28 12:43:03 24 4
gpt4 key购买 nike

我当时正在用 Swift 编写一个 iOS 应用程序。我创建了一个 TableView 场景,但它只显示它的第一个 subview 。我试图使代码尽可能简单。我创建了一个带有两个标签的表格 View 单元格,但它仍然只显示第一个标签。代码如下。为什么不显示第二个标签?我的 AutoLayout 约束错了吗?谢谢!

import UIKit

class TestCell: UITableViewCell {
let viewsDict: [String : UILabel] = [
"first": UILabel(),
"second": UILabel(),
]

override func awakeFromNib() {
viewsDict["first"]!.text = "first"
viewsDict["second"]!.text = "second"
viewsDict["first"]!.translatesAutoresizingMaskIntoConstraints = false
viewsDict["second"]!.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(viewsDict["first"]!)
contentView.addSubview(viewsDict["second"]!)
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[first]-[second]-|", options: [], metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[first]", options: [], metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[second]", options: [], metrics: nil, views: viewsDict))
}
}

class TableViewController: UITableViewController {

override func viewDidLoad() {
super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
}

}

最佳答案

从您的评论来看,您似乎在询问如何以编程方式自动设置单元格的高度。有几种不同的方法可以做到这一点:

最接近您可能想要的,在 iOS 8 及更高版本中,您可以让 tableView 自行计算:

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 60.0;

您也可以只设置 tableView 的 rowHeight 属性并让每一行的高度相同:

self.tableview.rowHeight = 60.0

或者您可以实现委托(delegate)方法来动态计算行高。这种方式还允许您检查每个单独的单元格并确定您应该制作多高的 View :

func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! TestCell
// Calculate the height that you want ..
let height = 60.0
return height
}

StackOverflow post更深入地探讨了自动调整 UITableViewCell 的大小。

关于ios - 以编程方式创建的 UITableViewCell 仅使用 AutoLayout 显示其第一个 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38944879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com