Высота UITableViewCell не настраивается автоматически (а вместо этого подавляет мой UIView), когда я пытаюсь добавить UIView программным способом - PullRequest
0 голосов
/ 29 мая 2018

Среда ... Swift 4.0, iOS 11.0 +

Новичок в разработке Swift и Apple здесь .. Я пытаюсь добавить UIView (различной высоты) в UITableViewCell.UIView, кажется, добавляется правильно, но UITableViewCell не регулирует свою высоту, чтобы показать весь UIView.

Столкнулся с этим: https://stackoverflow.com/a/36422189/3681880. Я попытался вернуться к основам, создав этот конкретный пример с нуля, чтобы убедиться, что высота строки ячеек регулируется в соответствии с размером этикетки.Это работает для меня, как и ожидалось.

Следующий шаг, я попытался добавить UIImageView в реализацию MyCustomCell, и вот где моя проблема ...

class MyCustomCell: UITableViewCell {

    @IBOutlet weak var myCellLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        let imageView = UIImageView(frame: CGRect(x:0.0,y:0.0,width:100.0,height:100.0))
        imageView.image = UIImage(named:"addData_20pt")

        contentView.addSubview(imageView)

        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 20).isActive = true
        imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10).isActive = true
        imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
    }
}

На скриншоте выможно увидеть, что все изображения сдавлены, чтобы поместиться в верхние ряды.Как заставить клетки расширяться, чтобы соответствовать изображениям вместо этого?

ужасный скриншот просмотра таблицы сейчас

(Извинения за действительно ужасный стол - только что скомбинировали это, чтобы понять концепцию!)

Для быстрогоссылка, это код ViewController из поста, на который есть ссылка

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    // These strings will be the data for the table view cells
    let animals: [String] = [
        "Ten horses:  horse horse horse horse horse horse horse horse horse horse ",
        "Three cows:  cow, cow, cow",
        "One camel:  camel",
        "Ninety-nine sheep:  sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep baaaa sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep",
        "Thirty goats:  goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat "]

    // Don't forget to enter this in IB also
    let cellReuseIdentifier = "cell"

    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // delegate and data source
        tableView.delegate = self
        tableView.dataSource = self

        // Along with auto layout, these are the keys for enabling variable cell height
        tableView.estimatedRowHeight = 44.0
        tableView.rowHeight = UITableViewAutomaticDimension
    }

    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.animals.count
    }

    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
        cell.myCellLabel.text = self.animals[indexPath.row]
        return cell
    }

    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }
}

Ответы [ 2 ]

0 голосов
/ 30 мая 2018

Добавление этого в качестве ответа для завершения ...

С помощью ответа Сергея мне удалось сделать это как в раскадровке, так и программно.Наиболее важным моментом была игра с ограничением «больше или равно».Спасибо, Сергей!

еще один уродливый скриншот таблицы с настройкой высоты строки ячейки

class MyCustomCell: UITableViewCell {

    @IBOutlet weak var myCellLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        let myView = UIImageView()
        myView.image = UIImage(named:"addData_20pt")
        contentView.addSubview(myView)
        myView.backgroundColor = UIColor.red
        myView.translatesAutoresizingMaskIntoConstraints = false
        myView.topAnchor.constraint(equalTo: myCellLabel.bottomAnchor, constant: 20).isActive = true
        myView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        myView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
        myView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
        myView.heightAnchor.constraint(greaterThanOrEqualToConstant: 100.0).isActive = true

    }
}
0 голосов
/ 29 мая 2018

Таким образом, вы установили размер своих ячеек только с вашим ярлыком.Я не знаю, как вы хотите видеть ваши ячейки, но если вы хотите, чтобы размер ваших ячеек изменялся в соответствии с меткой или imageView, то я бы посоветовал вам сделать следующее:

1) установить ваш imageView в XIBвместо кода

2) установите такие ограничения:

enter image description here

enter image description here

Ваше изображение вы можете установить в XIB или:

imageView.image = UIIMage(named: "YourImageName")

Мое решение выглядит так:

enter image description here

Или вы можетерасставьте все как хотите, поиграйте со свойством imageView "терка равных"

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...