Почему ограничение представления UITableViewCell dynamici c работает неправильно? - PullRequest
0 голосов
/ 16 февраля 2020

Я пытаюсь создать UIButton внутри UITableViewCell следующим образом:

Конфигурация UITableView:

self.tableView.estimatedRowHeight = 1
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.delegate = self
self.tableView.dataSource = self     

UITableViewCell:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {              
let uiTableViewCell = UITableViewCell(style: .default, reuseIdentifier: "More");
uiTableViewCell.contentView.backgroundColor = .yellow
let moreBtn = UIButton(type: .system)
moreBtn.setTitle("More", for: .normal)
moreBtn.setTitleColor(.white, for: .normal)
moreBtn.backgroundColor = UIColor.init(hexString: "#2A1771")

moreBtn.translatesAutoresizingMaskIntoConstraints = false
uiTableViewCell.contentView.addSubview(moreBtn)

let leading = NSLayoutConstraint(item: moreBtn, attribute: .leading, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .leading, multiplier: 1, constant: 16)
let trailing = NSLayoutConstraint(item: moreBtn, attribute: .trailing, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .trailing, multiplier: 1, constant: 16)
let top = NSLayoutConstraint(item: moreBtn, attribute: .top, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .top, multiplier: 1, constant: 16)
let bottom = NSLayoutConstraint(item: moreBtn, attribute: .bottom, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .bottom, multiplier: 1, constant: 16)

let height = NSLayoutConstraint(item: moreBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 52)

uiTableViewCell.contentView.addConstraints([leading,top,trailing,bottom,height])
NSLayoutConstraint.activate([leading,top,trailing,bottom,height])

return uiTableViewCell

}

См. Следующее изображение .. Почему еще кнопка выходит из contentView

enter image description here

1 Ответ

0 голосов
/ 16 февраля 2020

Ваши ограничения говорят, что задний край кнопки должен быть на 16 больше, чем задний край просмотра содержимого (константа +16), и аналогично для нижнего края.

Вы можете поменять местами item и toItem свойств в этих ограничениях или используйте -16 в качестве константы.

У вас также будет проблема с добавлением кнопки в cellForRow, так как ячейки используются повторно при прокрутке табличного представления, что приводит к нескольким кнопки добавляются в ячейку. Вы должны добавить кнопку в самой ячейке, либо в инициализаторе, либо в awakeFromNib

...