Я создаю пользовательский UITableViewCells с UILabel в каждом, но не могу получить ярлык для отображения в любом месте, кроме верхнего левого угла ячейки, looks like this.Ограничения макета для пользовательского UITtableViewCell не работают
Ограничения, по-видимому, не применяются, но они называются (достигая точки останова). Я попытался заменить UILabel на UIImageView и применить те же ограничения, но ничего не отображается (т. Е. Ячейки таблицы не заполнены).
Что мне не хватает?
Просмотр для клеток:
import UIKit
class myTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
}
let label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightLight)
label.text = "Sample"
label.backgroundColor = UIColor.red
return label
}()
func setupViews() {
addSubview(label)
//add constraints
let marginsGuide = self.contentView.layoutMarginsGuide
label.leadingAnchor.constraint(equalTo: marginsGuide.leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: marginsGuide.trailingAnchor).isActive = true
label.topAnchor.constraint(equalTo: marginsGuide.topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: marginsGuide.bottomAnchor).isActive = true
}
}
Посмотреть контроллер:
import UIKit
class myViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var myTableView: UITableView = UITableView()
var myArray = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
//... do stuff incl. loading data into my myArray
let screenSize: CGRect = UIScreen.main.bounds
self.myTableView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
self.myTableView.delegate = self
self.myTableView.dataSource = self
self.myTableView.register(IngredientListTableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(myTableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.myTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! myTableViewCell
return cell
}
}
Работы. Замечено также self.contentView.addSubview (label). Не могли бы вы помочь мне понять, что происходит? – kipepeo
В ячейке просмотра таблицы всегда используйте представление содержимого. Представление есть для содержимого ячейки. Отсюда и название. Ваш код не работал, потому что вы использовали поля представления содержимого ('let marginsGuide = self.contentView.layoutMarginsGuide'), но добавили subview к самой ячейке. – dasdom