иногда подвид загружается, но другие ячейки находятся поверх него
У меня есть UITableView, и когда пользователь касается строки, на экран добавляется подпредставление. Когда они щелкают другую строку, последнее подпредставление исчезает (и строка должна вернуться к своему нормальному размеру). Подпредставление отображается отлично (и исчезает при нажатии другой строки), но оно выходит за пределы строки и закрывает некоторые другие параметры. Кроме того, когда представление таблицы перезагружается после поворота экрана, подпредставление оказывается позади других строк таблицы.
Я хочу, чтобы строка с подпредставлением изменила размер так, чтобы она соответствовала фрейму подпредставления. Кроме того, каждое подпредставление имеет разный размер в зависимости от текста и изображений, включенных в него. Из-за этого я попытался использовать автоматические макеты и UITableViewAutomaticDimension, но, похоже, ничего не работает.
Я включаю свой UITableViewController, чтобы вы могли видеть, что у меня есть, и направлять меня в правильном направлении.
class TableViewController : UITableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.backgroundColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
self.tableView.estimatedRowHeight = rowHeight
return filmsToDisplay.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var currentFilm = filmsToDisplay[indexPath.row]
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.selectionStyle = .none
cell.textLabel?.text = "\(currentFilm.year) - \(currentFilm.movieTitle)"
cell.textLabel?.textColor = #colorLiteral(red: 0.254901975393295, green: 0.274509817361832, blue: 0.301960796117783, alpha: 1.0)
cell.textLabel?.font = UIFont.systemFont(ofSize: fontSize)
cell.textLabel?.sizeToFit()
cell.backgroundColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
cell.contentView.backgroundColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
let accessory = makeChart(currentFilm: filmsToDisplay[indexPath.row])
cell.contentView.addSubview(accessory)
accessory.translatesAutoresizingMaskIntoConstraints = false
accessory.trailingAnchor.constraint(equalTo:cell.contentView.trailingAnchor).isActive = true
accessory.topAnchor.constraint(equalTo: cell.contentView.topAnchor).isActive = true
accessory.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
accessory.widthAnchor.constraint(equalTo: cell.contentView.widthAnchor, multiplier: nomBarWidth).isActive = true
cell.contentView.translatesAutoresizingMaskIntoConstraints=false
cell.contentView.leadingAnchor.constraint(equalTo:cell.leadingAnchor).isActive = true
cell.contentView.trailingAnchor.constraint(equalTo:cell.trailingAnchor).isActive = true
cell.contentView.topAnchor.constraint(equalTo:cell.topAnchor).isActive = true
cell.contentView.bottomAnchor.constraint(equalTo: cell.bottomAnchor).isActive = true
return cell
}
var lastSelectedCell : UITableViewCell? = nil
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let currentFilm = filmsToDisplay[indexPath.row]
var detailView = createView(film: currentFilm)
detailView.tag = 555
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
//get rid of last detail view
if let lastCell = lastSelectedCell {
for i in 0..<lastCell.contentView.subviews.count {
let content = lastCell.contentView.subviews[i]
if content.tag == 555{
content.removeFromSuperview()
}
}
}
selectedCell.contentView.addSubview(detailView)
detailView.translatesAutoresizingMaskIntoConstraints=false
detailView.leadingAnchor.constraint(equalTo:selectedCell.contentView.leadingAnchor).isActive = true
detailView.trailingAnchor.constraint(equalTo:selectedCell.contentView.trailingAnchor).isActive = true
detailView.topAnchor.constraint(equalTo:selectedCell.contentView.topAnchor).isActive = true
detailView.bottomAnchor.constraint(equalTo:detailView.subviews[detailView.subviews.count - 2].bottomAnchor).isActive = true
lastSelectedCell = selectedCell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
Части подвидов определяют свою высоту следующим образом (есть больше частей, но все они имеют одинаковые ограничения:
//MOVIE TITLE BAR
let movieTitleBar = UIButton()
movieTitleBar.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: UIControlState.normal)
movieTitleBar.setTitle(film.movieTitle, for: UIControlState.normal)
movieTitleBar.backgroundColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
movieTitleBar.alpha = 0.5
movieTitleBar.layer.borderWidth = outlineWidth
movieTitleBar.layer.borderColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
}
filmView.addSubview(movieTitleBar)
movieTitleBar.translatesAutoresizingMaskIntoConstraints = false
movieTitleBar.topAnchor.constraint(equalTo:filmView.topAnchor).isActive = true
movieTitleBar.heightAnchor.constraint(equalToConstant: rowHeight).isActive = true
movieTitleBar.leadingAnchor.constraint(equalTo:filmView.leadingAnchor).isActive = true
movieTitleBar.trailingAnchor.constraint(equalTo:filmView.trailingAnchor).isActive = true
//POSTER IMAGE
var poster = UIButton()
isPoster = false
if let posterImg = film.image {
if let url = NSURL(string:posterImg){
if let data = NSData(contentsOf:url as URL){
film.poster = UIImage(data:data as Data)
poster.setImage(film.poster, for: UIControlState.normal)
isPoster = true
filmView.addSubview(poster)
}
}
}
//BRIEF DESCRIPTION LABEL
let briefDescriptionBar = UILabel()
briefDescriptionBar.backgroundColor = film.colorUI
briefDescriptionBar.alpha = 0.8
briefDescriptionBar.text = "\(film.year) - \(film.briefDescription)"
briefDescriptionBar.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
briefDescriptionBar.numberOfLines = 0
briefDescriptionBar.textAlignment = .center
filmView.addSubview(briefDescriptionBar)
briefDescriptionBar.translatesAutoresizingMaskIntoConstraints = false
briefDescriptionBar.leadingAnchor.constraint(equalTo:movieTitleBar.leadingAnchor).isActive = true
briefDescriptionBar.topAnchor.constraint(equalTo:movieTitleBar.bottomAnchor).isActive = true
if isPoster == true {
poster.translatesAutoresizingMaskIntoConstraints = false
poster.topAnchor.constraint(equalTo:movieTitleBar.bottomAnchor).isActive = true
poster.trailingAnchor.constraint(equalTo:movieTitleBar.trailingAnchor).isActive = true
poster.widthAnchor.constraint(equalTo:filmView.widthAnchor, multiplier:nomBarWidth).isActive = true
let aspect = (nomBarWidth * 41) / 27
poster.heightAnchor.constraint(equalTo: filmView.widthAnchor, multiplier: aspect).isActive = true
briefDescriptionBar.trailingAnchor.constraint(equalTo:poster.leadingAnchor).isActive = true
briefDescriptionBar.bottomAnchor.constraint(equalTo:poster.bottomAnchor).isActive = true
}
else {
briefDescriptionBar.widthAnchor.constraint(equalTo:filmView.widthAnchor).isActive = true
briefDescriptionBar.heightAnchor.constraint(equalTo:movieTitleBar.heightAnchor, multiplier : 2).isActive = true
}
Ваша проблема в том, что вы не устанавливаете ограничение по высоте для добавляемых подпредставлений, вы подключаете только ведущую, конечную, верхнюю и нижнюю части, но contentView ожидает ее высоты от внутренних подпредставлений (если у них нет внутреннего размера содержимого, такого как метки / кнопки), также нет необходимости в этой части кода
cell.contentView.translatesAutoresizingMaskIntoConstraints=false
cell.contentView.leadingAnchor.constraint(equalTo:cell.leadingAnchor).isActive = true
cell.contentView.trailingAnchor.constraint(equalTo:cell.trailingAnchor).isActive = true
cell.contentView.topAnchor.constraint(equalTo:cell.topAnchor).isActive = true
cell.contentView.bottomAnchor.constraint(equalTo: cell.bottomAnchor).isActive = true
Также должно быть только одно представление внутри contentView, которое подключено к нижней части, если вы добавите более одного, вы получите конфликты, если оба представления также подключены к верхней части, поэтому вам нужно сломать последнее представление снизу ограничение перед подключением нового
можете ли вы предоставить демо в github
Я просто погуглил, как это сделать, и похоже, что вам нужен Mac, но я на iPad Pro ... помогли бы скриншоты?
Я добавил скриншоты
согласно вашим фотографиям у вас есть таблица высоты 44 по умолчанию, созданная ios, когда высота не может быть введена
вы можете загрузить его на любой сайт, например mediaFire
Я не думаю, что смогу загрузить его с iPad ... Я могу только сфотографировать, сделать PDF-файл или снять видео. Я даже не могу поместить проект на свой iCloud Drive.
Я загрузил видео об этом здесь: mediafire.com/file/m7rbt7m7q61gya2/…
Я добавил часть кода изнутри вспомогательного представления. Все они имеют ограничения по высоте. Есть ли способ найти общую высоту, чтобы передать ее во фрейм субпредставления?