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.
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()
        }
    }
}
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()
        }
    }

Recommended Posts