简体   繁体   中英

How to change Label position using Auto layout

I have two label side by side "Label 1" and "Label 2". If "Label 1" content is not available then "Label 2" replace "Label 1" position. Do any one know how is it possible using auto layout? 在此处输入图片说明

For trying purpose, I have fixed height and weight for both Labels. "Label 1" have leading and Top 8 pixel margin, while "Label 2" have 0 pixel for leading and 8 pixel for Top. Set "Label 1" size to "0", Hide "Label 1" but it doesn't work.

If both the labels have fixed width , set constant width to both the labels. Set Lable2 leading space is '0' with respect to label1. Add a NSLayoutConstraint to the Label1 width. Now programatically when you found that Lable1 content is blank, set its width layout constraint to '0'. Lable2 will be automatically moved left and sits in the place of Label1.

Remove width constraint for both labels and update (set) compression/hugging priority for labels according to your requirement (from size inspector).

By removing width constraint your problem will be resolved, but autoLayout may show conflict for content display priority because of, your both labels are positioned, horizontally in a same line (points). To resolve this conflict, you need to update compression/hugging priority of any one of both labels.

Now, when there is no value for any one (or both) label text, set nil value for it, so its frame (space) will be automatically occupied by other label. And if both label text has nil value then both will be disappeared (automatically set their width to zero).

在此处输入图片说明

You need to create an IBOutlet of width constraint of Label2 and you need to check for content of Label1. If you found it blank then you need to set with to zero and call layoutIfNeeded to reset view frame.

If you dont want to work with compression/hugging properties. Then you can embed labels inside stackview and hide label when there is no content.

在此处输入图片说明

And when I hide label1

在此处输入图片说明

No constraints required :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM