Я пытаюсь использовать автоматическую компоновку, чтобы размер UITableViewCell всегда соответствовал его контенту.Размер авто UITableViewCell с двумя UILabels
Каждая ячейка содержит две этикетки topLabel
и bottomLabel
, которые вертикально сложены. Я хочу, чтобы обе надписи обертывались и отображали весь текст.
Я использую iOS8.
Вот мой код
class MyTableViewCell: UITableViewCell {
@IBOutlet var topLabel: UILabel!
@IBOutlet var bottomLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
topLabel = UILabel()
topLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
topLabel.numberOfLines = 0
contentView.addSubview(topLabel)
bottomLabel = UILabel()
bottomLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
bottomLabel.numberOfLines = 0
contentView.addSubview(bottomLabel)
let viewDictionary = ["topLabel": topLabel, "bottomLabel": bottomLabel]
var constraints = [NSLayoutConstraint]()
contentView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[topLabel]-|",
options:NSLayoutFormatOptions(0),
metrics: nil,
views: viewDictionary))
contentView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[bottomLabel]-|",
options:NSLayoutFormatOptions(0),
metrics: nil,
views: viewDictionary))
contentView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-[topLabel]-[bottomLabel]-|",
options:NSLayoutFormatOptions(0),
metrics: nil,
views: viewDictionary))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class MyTableViewController: UITableViewController, UITableViewDataSource {
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return 5;
}
override func viewDidLoad() {
tableView.rowHeight = UITableViewAutomaticDimension
super.viewDidLoad()
}
override func tableView(
tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
let cell = MyTableViewCell(
style: UITableViewCellStyle.Default,
reuseIdentifier: nil)
cell.topLabel.text = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26"
cell.bottomLabel.text = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
return cell
}
}
Однако только текст обручи верхней лейбла. В результате
Я не уверен, правильно ли я портя свои ограничения, или если есть другое свойство я должен установить, или же это просто не представляется возможным. Любая помощь будет принята с благодарностью.
Я боюсь, что я не могу дать вам код прямо сейчас, но обновляюсь по мере того, как я прихожу на свое место. –