So I have a checkbox and a label, I put them together within a UIView so I can use the checkbox and label as one component later on and for other projects, the thing is I want the view to change size (specifically width) according to the label text length. So far I can only seem to get this. The red part is a UIStackView containing the Checkbox and the label, the blue part is the UIView Class containing the stackView. What can I do to modify the Views size to match the Stackviews size, so if the label gets shorter so will the View. Thanks in advance!
CodePudding user response:
You need to use constraints. In this instance, you want the UIStackView to have constraint anchors each with a set value of zero for each side of the blue UIView - this will fill the blue UIView with the UIStackView.
Assuming that you will want the checkbox to remain the same size, you can set a width and height constraint, with a leading constraint of 0 to the left edge of the UIStackView.
Lastly, give the label constraints of 0 for the top and bottom edges of the UIStackView, and some number value for the leading and trailing constraints so that is has a bit of padding on either side of it (away from checkbox and right edge).
UIStackView Constraints
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: blueView.topAnchor, constant: 0).isActive = true
stackView.bottomAnchor.constraint(equalTo: blueView.bottomAnchor, constant: 0).isActive = true
stackView.leadingAnchor.constraint(equalTo: blueView.leadingAnchor, constant: 0).isActive = true
stackView.trailingAnchor.constraint(equalTo: blueView.trailingAnchor, constant: 0).isActive = true
CheckBox Constraints
checkBox.translatesAutoresizingMaskIntoConstraints = false
checkBox.topAnchor.constraint(equalTo: stackView.topAnchor, constant: 0).isActive = true
checkBox.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: 0).isActive = true
checkBox.heightAnchor.constraint(equalToConstant: given_height).isActive = true
checkBox.widthAnchor.constraint(equalToConstant: given_width).isActive = true
Label Constraints
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: stackView.topAnchor, constant: 0).isActive = true
label.bottomAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 0).isActive = true
label.leadingAnchor.constraint(equalTo: checkBox.trailingAnchor, constant: given_space).isActive = true
label.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: 0).isActive = true
In order for the view's height to adjust to the label (if its associated text is longer than one line), then add the following line of code:
label.numberOfLines = 0

