Henny Lee
Henny Lee

Reputation: 3062

Minimum spacing between labels relative to center of a view

I have two labels in my UITableViewCell and the constraints are set up so they are centered in the cell:

func setConsraints() {

    // horizontal constraints

    // vertical constraints
    mainLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: someVariable).isActive = true
    infoLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: -someVariable).isActive = true
}

normal (desired result)


But because the constant is a variable, sometimes it looks like:

overlapping (unwanted result)


I tried adding a constraint between mainLabel and infoLabel and played around with the priority but none of these solutions was working.

Question:

How can I add a "minimum" constraint to these two labels so they won't overlap each other but at the same time centering it to the UITableViewCell, maintaining a certain distance?

Upvotes: 1

Views: 289

Answers (2)

bitwit
bitwit

Reputation: 2676

What about putting them inside of a vertical UIStackView with the spacing you require and then center the stackview instead of the labels. This way you only have to manage the constraints of 1 view instead of 2.

Kind of like this: stackview setup

Upvotes: 3

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

Did you consider this alternative?

func setConsraints() {

    // horizontal constraints

    // vertical constraints
    mainLabel.bottomAnchor.constraint(equalTo: contentView.centerYAnchor, constant: -someVariable).isActive = true
    infoLabel.topAnchor.constraint(equalTo: contentView.centerYAnchor, constant: someVariable).isActive = true
}

Otherwise you need to get the height of the string and set the center anchor relative to that. There are string extensions which allow you to get the height of a string for a particular width like this answer. You can use that to get the height of the label and add half of that to someVariable in your approach.


Edit: I noticed that you have set a positive constant value for the mainLabel and negative for the infoLabel. If you want your mainLabel to be above the center then you need to add negative value to the mainLabel and the opposite for infoLabel.

Upvotes: 1

Related Questions