在我的UITableViewController
我有很多自定义单元格,其高度取决于它们内部的UITextView的长度。这意味着我无法从heightForRowAtIndexPath()
方法返回精确的大小,因为此时我还不知道。此外,因为我无法在@IBOutlet weak var
的约束条件中创建UITextView
,所以这里是我尝试过的代码:
let cell = tableView.dequeueReusableCellWithIdentifier("BigTextCell", forIndexPath: indexPath) as! BigTextCell
cell.backgroundColor = UIColor(patternImage: UIImage(named: "icons/background.png")!)
cell.paragraph.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1).CGColor
cell.paragraph.layer.borderWidth = 0.5
cell.paragraph.editable = false
cell.title.enabled = false
switch (indexPath.row) {
case 1:
cell.title.text = "Chi è:"
cell.icon.image = UIImage(named: "icons/field_fish.png")
cell.paragraph.text = self.fieldsCollection["life_method"] as! String
cell.paragraph.backgroundColor = UIColor(patternImage: UIImage(named: "icons/quadretti.png")!)
for constraint in cell.icon.constraints {
if (constraint.identifier == "icon_width") {
constraint.constant = 64.0
break
}
}
for constraint in cell.paragraph.constraints {
if (constraint.identifier == "longTextConstraint") {
constraint.constant = cell.paragraph.sizeThatFits(CGSize(width: cell.paragraph.frame.width, height: CGFloat.max)).height
break
}
}
...
因此,UITextView
根据文本的长度正确地调整大小,但通常单元格的高度太大。我怎样才能解决这个问题?
谢谢
更新
正如你们有人建议的那样,如果我在heightForRowAtIndexPath
if (indexPath.row == 1) {
//return 235.0
let cell = tableView.dequeueReusableCellWithIdentifier("BigTextCell", forIndexPath: indexPath) as! BigTextCell
cell.paragraph.text = self.fieldsCollection["life_method"] as! String
for constraint in cell.paragraph.constraints {
if (constraint.identifier == "longTextConstraint") {
constraint.constant = cell.paragraph.sizeThatFits(CGSize(width: cell.paragraph.frame.width, height: CGFloat.max)).height
return constraint.constant+30.0
break
}
}
}
模拟器阻止。
答案 0 :(得分:1)
您可以在每个tableView.rowHeight = UITableViewAutomaticDimension
方法调用中设置heightForRowAtIndexPath()
或计算适当文本的单元格高度。
答案 1 :(得分:1)
在class ViewController: UIViewController {
@IBOutlet var theTextField: UITextField!
@IBAction func buttonTapped(sender: AnyObject) {
theTextField.resignFirstResponder()
}
}
方法中尝试此操作:
viewDidLoad
答案 2 :(得分:0)
你可以(并且应该)返回- tableView:heightForRowAtIndexPath:
和- tableView:estimatedHeightForRowAtIndexPath:
的确切高度(不一定是这里的确切高度,但是越接近越好,如果值不够精确,你可能会得到视觉如果您正在使用它,则会出现故障和autolayout问题)。计算中唯一缺少的是单元实例,您可以通过调用相应的方法cellForRowAtIndexPath或使用您从未显示但用于计算的静态单元实例从表视图中获取它。前者快速且易于使用,后者具有其自己的特定用例,例如,如果你出于某种原因想要计算单元格的高度,而不需要实际的表视图。
请注意,即使UITableView
和UITableViewDataSource
分别具有相似签名的方法- cellForRowAtIndexPath
和
- tableView:cellForRowAtIndexPath:
,它们的功能也不同,表视图的方法可以返回{{ 1}},请参阅文档了解详细信息。