Automatically set the width and height of the UI Label

Introduction

Since I started to create layouts based on code using SnapKit, I have become aware of the width and height of UI parts that have text. Here, I will keep a record of how to set width and height automatically.

Trouble

Simulator Screen Shot - iPhone 12 - 2021-01-06 at 17.53.19.png I tried to create a layout based on the code base, but the width and height settings didn't work! Or rather, it's messy!

private func setupLabel() {
        label.text = "AIUEO"
        label.backgroundColor = .red
        view.addSubview(label)
        label.snp.makeConstraints {
            $0.width.equalTo(60)//Since this is a constant, you have to check it many times until it feels good.
            $0.height.equalTo(30)//Similarly
            $0.center.equalToSuperview()
        }
    }
}

Solutions

Use sizeThatFits and greatestFiniteMagnitude.

private func setupLabel() {
        label.text = "AIUEO"
        label.backgroundColor = .red
        let size = label.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
        view.addSubview(label)
        label.snp.makeConstraints {
            $0.width.equalTo(size.width)
            $0.height.equalTo(size.height)
            $0.center.equalToSuperview()
        }
    }

Simulator Screen Shot - iPhone 12 - 2021-01-06 at 17.57.47.png

Recommended Posts

Automatically set the width and height of the UI Label
Why the width of the full screen element is 100% and the height is 100vh
[Swift] Set the margins for multiple lines of UI Label: top, bottom, left, and right
This and that of the JDK
Difference between byCharWrapping and byWordWrapping of UI Label in Japanese display
[Android] Dynamically set the height of ListView with copy (for beginners)
Folding and unfolding the contents of the Recyclerview
About the operation of next () and nextLine ()
[Swift] Get the height of Safe Area
[Rails] Change the label name of f.label
About the mechanism of the Web and HTTP
Fn Project Beginning-Introduction of Fn Server and UI
[Java] Understand the difference between List and Set
[Order method] Set the order of data in Rails
Check the version of the JDK installed and the version of the JDK enabled
Compare the speed of the for statement and the extended for statement.
[Java] The confusing part of String and StringBuilder
Set the time of LocalDateTime to a specific time
I compared the characteristics of Java and .NET
Learn the rudimentary mechanism and usage of Gradle 4.4
About next () and nextLine () of the Scanner class
What are the advantages of DI and Thymeleaf?
How to set the retry limit of sidekiq and notify dead queues with slack