UIView изменить размер, чтобы разместить ярлыки внутри него - PullRequest
0 голосов
/ 25 мая 2018

У меня есть UIView, который я добавляю в представление стека на моей главной странице моего приложения

Это класс моего представления:

class MyCustomView: UIView {
    public let leftLabel: UILabel = UILabel(frame: .zero)
    public let rightLabel: UILabel = UILabel(frame: .zero)

    override init(frame: CGRect) {
        super.init(frame: frame)

        addSubview(leftLabel)
        addSubview(rightLabel)

        leftLabel.translatesAutoresizingMaskIntoConstraints = false
        rightLabel.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            leftLabel.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.4),
            leftLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
            leftLabel.topAnchor.constraint(equalTo: topAnchor),
            leftLabel.bottomAnchor.constraint(equalTo: bottomAnchor),

            rightLabel.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.6),
            rightLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
            rightLabel.topAnchor.constraint(equalTo: topAnchor),
            rightLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
        ])
        leftLabel.text = "Short string"
        rightLabel.text = "Short string too"
    }
}

И я добавляю кмой основной вид стека с: let myCustomView = MyCustomView(frame: .zero) stackView.addArrangedSubview(myCustomView)

Это загружается в мой ярлык правильно и изменяет размер всего, как я хотел.

Однако в моем основном классе я обновляю myCustomView.rightLabel.text = <New Way Longer Text That Takes 2 Lines Instead of One>

Текст корректно обновляется, но мой размер myCustomView не изменяется, поэтому часть текста просто обрезается

Я попробовал следующие ответы здесь,но ни один из них, похоже, не работает для меня.

Я что-то упустил, чтобы изменить размер настраиваемого представления, чтобы он соответствовал метке внутри него?

Заранее спасибо

1 Ответ

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

Ваш код не показывает, что вы установили .numberOfLines в метках для 0, чтобы разрешить использование многострочных меток.

Добавление только этого должно позволить вашим меткам расти ввысота и расширить свой пользовательский вид.Однако ... это также заставит обе метки расширяться до размера самой высокой метки, в результате чего текст "более короткой" метки будет центрирован по вертикали (я добавил цвета фона, чтобы было легче видеть рамки / границы видов):

enter image description here

Если вы ограничите нижнюю часть своего пользовательского представления до нижней части каждой метки на greaterThanOrEqualTo, вы можете оставить метки "top-выровнен ":

enter image description here

Вы можете запустить этот код прямо на странице игровой площадки, чтобы увидеть результаты:

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyCustomView: UIView {
    public let leftLabel: UILabel = UILabel(frame: .zero)
    public let rightLabel: UILabel = UILabel(frame: .zero)

    override init(frame: CGRect) {
        super.init(frame: frame)

        addSubview(leftLabel)
        addSubview(rightLabel)

        // background colors so we can see the view frames
        backgroundColor = .cyan

        leftLabel.backgroundColor = .yellow
        rightLabel.backgroundColor = .green

        // we want multi-line labels
        leftLabel.numberOfLines = 0
        rightLabel.numberOfLines = 0

        // use auto-layout
        leftLabel.translatesAutoresizingMaskIntoConstraints = false
        rightLabel.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            // constrain to top
            leftLabel.topAnchor.constraint(equalTo: topAnchor),
            // constrain to left
            leftLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
            // constrain width = 40%
            leftLabel.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.4),

            // constrain to top
            rightLabel.topAnchor.constraint(equalTo: topAnchor),
            // constrain to right
            rightLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
            // constrain width = 60%
            rightLabel.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.6),

            // constrain bottom of view (self) to >= 0 from bottom of leftLabel
            bottomAnchor.constraint(greaterThanOrEqualTo: leftLabel.bottomAnchor, constant: 0.0),
            // constrain bottom of view (self) to >= 0 from bottom of rightLabel
            bottomAnchor.constraint(greaterThanOrEqualTo: rightLabel.bottomAnchor, constant: 0.0),
            ])

        leftLabel.text = "Short string"
        rightLabel.text = "Short string too"
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class MyViewController : UIViewController {

    var theButton: UIButton = {
        let b = UIButton()
        b.setTitle("Tap Me", for: .normal)
        b.translatesAutoresizingMaskIntoConstraints = false
        b.backgroundColor = .red
        return b
    }()

    var theStackView: UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.axis = .vertical
        v.spacing = 8
        v.distribution = .equalSpacing
        return v
    }()

    var myView = MyCustomView()

    // on button tap, change the text in the label(s)
    @objc func didTap(_ sender: Any?) -> Void {
        myView.leftLabel.text = "Short string with\nA\nB\nC\nD\nE"
        myView.rightLabel.text = "Short string too\nA\nB"
    }

    override func loadView() {
        let view = UIView()
        self.view = view

        view.backgroundColor = .white

        view.addSubview(theButton)
        // constrain button to Top: 32 and centerX
        NSLayoutConstraint.activate([
            theButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 32.0),
            theButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0),
            ])

        view.addSubview(theStackView)

        // constrain stack view to Top: 100 and Leading/Trailing" 0
        // no Bottom or Height constraint
        NSLayoutConstraint.activate([
            theStackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100.0),
            theStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0),
            theStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0),
            ])

        theStackView.addArrangedSubview(myView)

        // add an action for the button tap
        theButton.addTarget(self, action: #selector(didTap(_:)), for: .touchUpInside)

    }
}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...