ios – The right way to preserve UIView top constant when UILabel textual content varies between 1 and three strains?

0
26
ios – The right way to preserve UIView top constant when UILabel textual content varies between 1 and three strains?


I’ve a view construction applied in Swift utilizing UIKit the place a UIView incorporates a UILabel. The UILabel can have textual content with 1 line at minimal and as much as 3 strains at most. I wish to make sure that the UIView’s top stays constant even when the UILabel has just one line of textual content.

Listed below are the main points:

The UIView has 12-point constraints on all edges (high, main, backside, and trailing) to the UILabel.
The UILabel ought to develop to accommodate as much as 3 strains, however the UIView ought to stay the identical top even when the textual content has just one line.
How can I add a constraint to the UIView to make sure its top stays the identical no matter whether or not the UILabel has 1 line or as much as 3 strains of textual content?

Any assist or steerage could be vastly appreciated!

enter image description here

At this level, my code is one thing like beneath.

class ViewController: UIViewController {

    override func viewDidLoad() {
        tremendous.viewDidLoad()

        // Create the mum or dad view (container for the UILabel)
        let containerView = UIView()
        containerView.translatesAutoresizingMaskIntoConstraints = false
        containerView.backgroundColor = .lightGray
        view.addSubview(containerView)

        // Create the UILabel
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 3 // Max variety of strains
        label.textual content = "It is a pattern textual content for UILabel"
        label.font = UIFont.systemFont(ofSize: 17)

        containerView.addSubview(label)

        // Add constraints for the containerView (assuming it has 12 factors padding to the perimeters)
        NSLayoutConstraint.activate([
            containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            containerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100)
        ])

        // Add constraints for the UILabel inside the containerView
        NSLayoutConstraint.activate([
            label.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 12),
            label.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -12),
            label.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 12),
            label.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -12)
        ])
    }
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here