Why a frame of a UIView is not updating in ViewDid

2020-07-03 06:39发布

I am trying to update the frame of a UIView which contains buttons and labels inside. I am trying to update it in viewDidLayoutSubviews (and I also tried in viewDidLoad, viewWillAppear, viewDidAppear..). I want to change the y position (origin.y) of the view. The NSLogs says my original y position is 334, and after changing, it is 100. However, the position does not change in my view. I have already checked that the view is connected in the storyboard. What am I doing wrong?

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    CGRect theFrame  = [self.bottomView frame];
    NSLog(@"Y position bottomview: %f", self.bottomView.frame.origin.y);

    if([[UIScreen mainScreen] bounds].size.height == 568) //iPhone 4inch
    {
       // NSLog(@"iphone5");
    }
    else{
       // NSLog(@"iphone4");
        theFrame .origin.y =  100;
    }

    self.bottomView.frame = theFrame;
    NSLog(@"Y position bottomview after changing it: %f", self.bottomView.frame.origin.y);
    [self.view layoutIfNeeded];
}

4条回答
我命由我不由天
2楼-- · 2020-07-03 07:10

The frame setting should work in your code. But if the view has autolayout constraints (which I assume you have), your frame setting won't work. You can only go one way or the other (manual frame setting or autolayout), not both.

查看更多
你好瞎i
3楼-- · 2020-07-03 07:12

The problem was related with Autolayout. However I couldn't turn it off since I am using autolayout in my project. I solved defining appropriate constraints in the view. Then there is no need to check if it is iPhone 4inch or 3.5inch and change the position of the frame since it automatically adapts to each size.

查看更多
劳资没心,怎么记你
4楼-- · 2020-07-03 07:22

Believe it or not the below code fixed it

override func viewDidLayoutSubviews() {
    DispatchQueue.main.async {
        // UI changes
    }
}
查看更多
家丑人穷心不美
5楼-- · 2020-07-03 07:31

I've had the same problem. Forcing the layouting for your view's superview helped me out:

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [self.bottomView.superview setNeedsLayout];
    [self.bottomView.superview layoutIfNeeded];

    // Now modify bottomView's frame here
}

In Swift:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    bottomView.superview!.setNeedsLayout()
    bottomView.superview!.layoutIfNeeded()

    // Now modify bottomView's frame here
}
查看更多
登录 后发表回答