Как получить ширину UILabel при расчете по ограничениям - PullRequest
0 голосов
/ 29 мая 2018

Я не хочу рисовать теги на экране и размещать их слева направо, а в случае, если их слишком много для 1 строки, переходите на новую строку.Вот так:

Image of example of what I need

В настоящее время я застрял, я не знаю, как получить ширину метки после ее вычисления по ограничениям.Мне нужно найти, что tagWidth

enum TagPosition {
    case left_top
    case left
    case top
    case other
}

func createProductTags() {
    var lineWidth: CGFloat = 8.0
    var line = 0
    var lastTag: UIView = self.contentView
    var position = TagPosition.other
    var viewAbove = self.contentView

    for i in 0..<menu.tagName.count {
        if (line == 0 && lineWidth == 8.0) {
            position = TagPosition.left_top
        } else if (line == 0) {
            position = TagPosition.top
        } else if (lineWidth == 8.0) {
            position = TagPosition.left
        } else {
            position = TagPosition.other
        }
        self.tag = setTagSettings(named: menu.tagName[i], position: position)
        var tagConstraints = setTagConstraints(lastTag: lastTag, viewAbove: viewAbove, position: position)
        lineWidth += tagWidth + 8.0
        if (lineWidth > self.contentView.bounds.width - 16) {
            viewAbove = lastTag
            updateConstraintWhenNewLine(tagConstraints: &tagConstraints, viewAbove: viewAbove)
            line += 1
            lineWidth = tagWidth + 16.0
        }
        lastTag = self.tag
    }
    // To fit the contentView to the last line of tags
    lastTag.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor).isActive = true
}

func updateConstraintWhenNewLine(tagConstraints: inout [NSLayoutConstraint], viewAbove: UIView) {
    // Change constraints of last label of the line if it doesn't fit on the line
    //Remove old contraints
    topConstraint.isActive = false
    leftConstraint.isActive = false
    tagConstraints.remove(object: topConstraint)
    tagConstraints.remove(object: leftConstraint)
    self.tag.removeConstraints([topConstraint, leftConstraint])

    //Add old contraints
    topConstraint = self.tag.topAnchor.constraint(equalTo: viewAbove.bottomAnchor, constant: 8)
    leftConstraint = self.tag.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 16)
    tagConstraints.append(contentsOf: [topConstraint, leftConstraint])
    NSLayoutConstraint.activate([topConstraint, leftConstraint])
}

func setTagSettings(named tagName: String, position: TagPosition) -> UIView {
    // tagContainer settings
    let tagContainer = UIView()
    tagContainer.backgroundColor = DiscoderyAppSettings.sharedInstance.primaryColor
    tagContainer.layer.masksToBounds = true
    tagContainer.layer.cornerRadius = self.tagHeight / 2
    tagContainer.translatesAutoresizingMaskIntoConstraints = false
    self.contentView.addSubview(tagContainer)

    // tagLabel settings
    let tagLabel = UILabel()
    tagLabel.text = tagName
    tagLabel.font?.withSize(16.0)
    tagLabel.textColor = UIColor.white
    tagLabel.textAlignment = .center
    tagLabel.translatesAutoresizingMaskIntoConstraints = false
    tagContainer.addSubview(tagLabel)

    // tagLabel constraints
    tagLabel.topAnchor.constraint(equalTo: tagContainer.topAnchor).isActive = true
    tagLabel.leftAnchor.constraint(equalTo: tagContainer.leftAnchor, constant: 8).isActive = true
    tagLabel.rightAnchor.constraint(equalTo: tagContainer.rightAnchor, constant: -8).isActive = true
    tagLabel.bottomAnchor.constraint(equalTo: tagContainer.bottomAnchor).isActive = true

    return tagContainer
}

func setTagConstraints(lastTag: UIView, viewAbove: UIView, position: TagPosition) -> [NSLayoutConstraint] {

    var tagConstraints: [NSLayoutConstraint] = [NSLayoutConstraint]()
    heightConstraint = self.tag.heightAnchor.constraint(equalToConstant: tagHeight)

    switch position {
    case .left_top:
        topConstraint = self.tag.topAnchor.constraint(equalTo: self.contentView.topAnchor)
        leftConstraint = self.tag.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 16)
    case .left:
        topConstraint = self.tag.topAnchor.constraint(equalTo: viewAbove.bottomAnchor, constant: 8)
        leftConstraint = self.tag.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 16)
    case .top:
        topConstraint = self.tag.topAnchor.constraint(equalTo: self.contentView.topAnchor)
        leftConstraint = self.tag.leftAnchor.constraint(equalTo: lastTag.rightAnchor, constant: 8)
    default:
        topConstraint = self.tag.topAnchor.constraint(equalTo: viewAbove.bottomAnchor, constant: 8)
        leftConstraint = self.tag.leftAnchor.constraint(equalTo: lastTag.rightAnchor, constant: 8)
    }
    tagConstraints.append(contentsOf: [heightConstraint, topConstraint, leftConstraint])
    NSLayoutConstraint.activate(tagConstraints)
    return constraints
}

createProductTags() вызывается в func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

Если вам нужны какие-либо другие детали, спросите меня.Спасибо

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