Среда ... 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).")
}
}