I have seen several questions regarding this topic; however, none of them resolved the issue, and for the life of me I cannot figure out why the constraints are not taking effect. (Maybe because I haven't slept in a while.. I know it's counterproductive).
I am new to IOS development, but I'm hitting it hard and a quick learner. If you could provide an explanation as to why my original code was not working that would be super helpful. Thumbs up to whoever can resolve issue!
Okay, so I'm developing an app that I've actually been working on for quite a while & I did a real sloppy job when I first began. So I'm basically rebuilding the app's code but completely cutting out the Interface Builder (Storyboard). I am trying to pin a UIButton to a UIView locally (I'd rather not declare it globally).
// parentView initialized //
parentView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
[parentView setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:parentView];
parentView.tag = 0;
// homeScreenView initialized //
homeScreenView=[[UIView alloc]initWithFrame:CGRectMake(0, homeScreenTitle.frame.size.height, screenWidth, screenHeight-homeScreenTitle.frame.size.height-height)];
[homeScreenView setBackgroundColor:[UIColor greenColor]];
[parentView addSubview:homeScreenView];
homeScreenView.tag = 2;
// chatMenuView initialized //
chatMenuView=[[UIView alloc]initWithFrame:CGRectMake(0, homeScreenTitle.frame.size.height+10, 100, screenHeight-height-10-10-homeScreenTitle.frame.size.height)];
[chatMenuView setBackgroundColor:[UIColor grayColor]];
[parentView addSubview:chatMenuView];
chatMenuView.tag = 3;
// chatMenuButton initialized //
chatMenuButton = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *buttonText = [NSString stringWithFormat:@"CHAT"];
[chatMenuButton setTitle:buttonText forState:UIControlStateNormal];
[parentView addSubview:chatMenuButton];
[chatMenuButton sizeToFit];
chatMenuButton.center = CGPointMake(0,screenHeight/2);
UIImage *chatIcon = [UIImage imageNamed:@"GrayHouse1.png"];
[chatMenuButton setBackgroundImage:chatIcon forState:(UIControlStateNormal)];
chatMenuButton.tag = 5;
// pinChatButton //
NSLayoutConstraint *pinChat = [NSLayoutConstraint constraintWithItem:chatMenuView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:chatMenuButton
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:0];
[self.view addConstraint: pinChat];
I would like to also add that all of this code is in the viewDidLoad method & all of the other views are declared in the header file (as IBOutlets).Basically when I run the code, the UIView leading margin is at position x = 100, and the button is at position x = 0 which is what it's suppose to be at prior to adding constraints which should also move the button to position x = 100.
translatesAutoresizingMaskIntoConstraintstoNOfor all views you want to addNSLayoutConstraint.