简体   繁体   中英

Position UILabel relative to UIImage in Universal Storyboard using Autolayout Xcode6

I am implementing a custom map view in which I want to add multiple UILabels over an UIImage. Below is the view hierarchy:

视图层次

When I preview it on iPhone & iPad, UILabel stays relative to the SuperView but I want to stay it relative to a point(x,y) in UIImage so that whatever be the the device, the label should always be with Groovy room.

I can draw text on UIImage, but it is a very costly operation in my scenario as my View will be loaded once & I need to update the label frequently.

Below is the current UI:

当前用户界面

As shown, label doesn't stay in Groovy room & goes out of the way.

You need to pin the UILabel to the leading left and top of the UIImageView you wish it to layout relative to. Set the pin offsets to be the relative x and y you wish.

Updated after comments

If you have one big image that will fill the screen and you want to position multiple labels, I think you are going to have to do the positioning in code. The reason I say this is that for different screen sizes you need to change the point the image is shown at.

Suggestion is|

1) For your map, create a table containing the relative position for the centre of each room. Eg Centre of Room 1 is 25% across and 10% down. Put then in an array. You now have a way of defining the centre if each room regardless of screen size.

2) In your viewDidLoad method, create your UILabels and put them in an array indexed by room number. Add the labels to your main view. You could do this in storyboard if you have an exact number and assign IBOutlets you can put in an array.

3) Implement layoutSubviews and in there set the centre of each label to be the centre of the room plus an offset so it shows below the room label. Call super version first. Use the centre property of the UILabel frame to make this easy. Doing this in layoutSubviews should work around any issues with constraints the system adds itself.

This should let you handle labels for all screen sizes as you are coding the label positions as relative to the image. When running you are converting this relative position to actual points.

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