Search code examples
iosios7

After adding constrain scrolling not work


i am trying to add button inside the scrollview with center constrain, constrain working but scroll not working scroll become stuck, Anyone can help me where is mistake,

-(void)viewDidLoad{
scrllview = [[UIScrollView alloc] initWithFrame:
                 [[UIScreen mainScreen] applicationFrame]];
    scrllview.backgroundColor = [UIColor orangeColor];
    self.view=scrllview;
    [scrllview setContentSize:CGSizeMake(300, 1000)];


    submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [submitButton setTitle:@"connect" forState:UIControlStateNormal];
    [submitButton.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14.0]];
    [submitButton addTarget:self
                     action:@selector(myMethod:)
           forControlEvents:UIControlEventTouchUpInside];
    submitButton.backgroundColor = [UIColor blackColor];
    submitButton.translatesAutoresizingMaskIntoConstraints = NO ;
    [scrllview addSubview:submitButton];

    NSLayoutConstraint *constraint = [NSLayoutConstraint
                                      constraintWithItem:submitButton
                                      attribute:NSLayoutAttributeCenterX
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:scrllview
                                      attribute:NSLayoutAttributeCenterX
                                      multiplier:1.0f
                                      constant:0.0f];

    [scrllview addConstraint:constraint];

    constraint = [NSLayoutConstraint
                  constraintWithItem:submitButton
                  attribute:NSLayoutAttributeCenterY
                  relatedBy:NSLayoutRelationEqual
                  toItem:scrllview
                  attribute:NSLayoutAttributeCenterY
                  multiplier:1.0f
                  constant:0.0f];

    [scrllview addConstraint:constraint];
}

Solution

  • While you are using scrollview with autolayout, you should not use contentsize.

    You can create a view inside scroll view, which should have your required height and constraint relative to scrollview. You can add your button inside that view.

    It will work. I have implemented it with xib. Same issue while adding control directly in scrollview. I used view inside scrollview and added required control to view.

    Auto layout UIScrollView with subviews with dynamic heights