Reputation: 6823
I have created a very basic circle view. Which simply calls a custom Init method which sets the layer radius to be half of its width. The View Controller creates the subview, adds it, and then sets up constraints to center the circle.
Note: I have checked multiple SO answers on the same question and the constraints appear to be setup correctly/the same.
The issue is that when the constraints are added the view does not show. I have logged out the circleView bounds and frame and they both show as 0,0,100,100 which is what the frame is initially set as, but the view does not show at all? Removing the constraints the frame is 0,0,100,100 and shows in this location. So it appears adding the constraints makes the view disappear.
- (void)viewDidLoad
{
NSLog(@"%s",__PRETTY_FUNCTION__);
[super viewDidLoad];
[self setupViewControllerViews];
}
-(void)setupViewControllerViews {
self.circleView = [[CCZTCircleView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[self.view addSubview:self.circleView];
[self setupCircleViewAutoLayoutConstraints];
}
-(void)setupCircleViewAutoLayoutConstraints {
NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:self.circleView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:self.circleView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
[self.view addConstraint:xCenterConstraint];
[self.view addConstraint:yCenterConstraint];
}
Upvotes: 0
Views: 261
Reputation: 2547
The frame you set at the beginning is ignored if you use auto layout, as with auto layout Cocoa touch will change your view's frame accordingly on the base of the constraints you set. Add the following lines to the method were you setup the constraints to obtain the expected result (what you need is setting up a fixed height and a fixed width constraints):
UIView *view = self.circleView;
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[view(100)]"
options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)];
[self.view addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[view(100)]"
options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)];
[self.view addConstraints:constraints];
When you create your view is therefore superfluous to specify any frame as it will be defined by auto layout - I find useful to instantiate my views simply like [[UIView alloc] init]
so that I clearly show in the code that frames are not directly involved.
Upvotes: 1