私のUITableViewController
には、高さがUITextViewの長さに依存する多くのカスタムセルがあります。これは、正確なサイズをheightForRowAtIndexPath()
メソッドから返すことができないことを意味します。なぜなら、私はその時点でまだそれを知ることができないからです。また、私はUITextView
を支配制約に@IBOutlet weak var
を作成することはできませんとして、ここで私が試してみましたコードだ:Swift:cellForRowAtIndexPathメソッドでUITableViewCellを設定する方法
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
}
}
}
シミュレータブロックでこれをしようとした場合 は、あなた
UPDATE ありがとうございます。
ので、私は私が '' heightForRowAtIndexPathにcellForRowAtIndexPath' 'で行う同じ説明を繰り返すなければなりませんか?さらに、私が 'UITableViewAutomaticDimension'を使うと、同じ高さのセルが得られます... –
本当にUITextViewが必要ですか?テキストに合わせてサイズを調整できるUILabelを使用できますか? heightForRowAtIndexPathでは、現在のインデックスパスのテキストを取得し、そのテキストの高さを計算する必要があります([link](http://stackoverflow.com/questions/19128797/calculating-uilabel-text-size)を参照)。 – Sunny
'UITableViewAutomaticDimension'を使うときは、' tableView:estimatedHeightForRowAtIndexPath: 'で意味のある値を返す必要があります。まだ動作しない場合は、制約をチェックする必要があります。テーブルビューで自動ディメンションを使用すると、非常に便利ですが、バグがないわけではありません。古い代替案を使用する準備ができています。 –