Добавление программной метки с относительной проблемой ограничения - PullRequest
1 голос
/ 04 апреля 2019

У меня есть UITableView с некоторыми ячейками, в первую ячейку я хотел бы добавить несколько UILabel. Это код, который я использую внутри функции в подклассе UITableViewCell (вызывается в cellForRowAt):

    ...
let constantTop = 16


    for (index,optional) in optionals.enumerated(){
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "\(optional.name)"
        label.tag = 10010132
        label.font = CocoFonts.semibold(size: 15)
        label.textColor = CocoColors.FedericoMalagoni.textVeryDarkBlue

        self.contentView.addSubview(label)
        let constant:CGFloat = CGFloat(constantTop * (index + 1))

        print(constant)

        let horizontalConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 16)

        let verticalConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 16)

        let height = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 20)


        let top = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.lblInfo, attribute: NSLayoutAttribute.bottomMargin, multiplier: 1, constant: constant)

        let bottom = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: constant)


        NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, top, bottom, height])

    }
    self.contentView.setNeedsUpdateConstraints()
    self.contentView.setNeedsLayout()
    self.contentView.layoutIfNeeded()
...

Теперь, Ярлыки расположены по краю ячейки следующим образом:

enter image description here

Серый разделитель разделяет ячейку. По сути, высота ячейки не обновляется.

1 Ответ

0 голосов
/ 04 апреля 2019

Было бы более понятно, если бы вы могли поделиться полной реализацией cellForRowAt. Я столкнулся с подобной проблемой, когда содержимое ячеек перекрывалось. Я добавил пользовательский вид в ячейку как подпредставление.

Это происходит потому, что табличное представление использует свои ячейки. Поэтому одним из решений является удаление старой метки из ячейки перед добавлением новой.

for content in cell.contentView.subviews {
   content.removeFromSuperview()
} 
...