Programmatically moving a UILabel in a xib file

2019-06-26 17:31发布

问题:

Problem: My UILabel is not moving after I change its frame information but after outputing with NSLog the frame info matches the correct position, yet the label itself does not actually move.

More Info: I'm trying to move a UILabel to the same position as a UITextField. Both are contained in a XIB file. I can update the text just fine, and outputting frame information would indicate that the label has moved to the correct position but when you actually look on the screen you can see the label is exactly wherever I placed it in the XIB file manually; it hasn't moved.

photoDescriptionLabel is the UILabel I am trying to place on-top of photoDescription which is a UITextField. The text field is made invisible and made visible so you only see the label until its time to edit it, at which time I hide the label and make the text field visible.

CODE - Taken from inside corresponding ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.photoDescriptionLabel.frame = CGRectMake(self.photoDescription.frame.origin.x,self.photoDescription.frame.origin.y,self.photoDescriptionLabel.frame.size.width,self.photoDescriptionLabel.frame.size.height);        
    self.photoDescription.hidden = YES;
    self.photoDescriptionLabel.hidden = NO;
    NSLog(@"x: %f, y: %f, width: %f, height: %f ",self.photoDescriptionLabel.frame.origin.x,self.photoDescriptionLabel.frame.origin.y,self.photoDescriptionLabel.frame.size.width,self.photoDescriptionLabel.frame.size.height);        

}

回答1:

I think you have to switch off the main view's "Use Autolayout" flag in Interface Builder. Auto Layout is enabled by default when you create a new project.



回答2:

Try this:

CGRect frame = self.photoDescriptionLabel.frame;
frame.origin.x = self.photoDescription.frame.origin.x;
frame.origin.y = self.photoDescription.frame.origin.y;
self.photoDescriptionLabel.frame = frame;