无法使用自动布局设置按钮的宽度

时间:2015-08-03 13:36:12

标签: ios objective-c uiscrollview autolayout nslayoutconstraint

我是自动布局的新手,在scrollview中使用了自动布局我在uiscrollview中有一些简单的设置,但我没有实现它。

首先想我需要讨论的是我在编码中使用autolayout而不是在故事板中。

我有20个宽度和高度相同的按钮,想要在uiscrollview中设置。

但令我惊讶的是我的按钮宽度设置为包含插入。我尝试了很多R& D但无法找到解决方案

我的代码正在关注

 UIScrollView *sview = [[UIScrollView alloc] init];
    [sview setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.7]];
    [sview setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addSubview:sview];





    NSDictionary *dict = NSDictionaryOfVariableBindings(sview);
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[sview]|" options:0 metrics:nil views:dict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-60-[sview]-|" options:0 metrics:nil views:dict]];

设置scrollview,其宽度与视图相同

 NSMutableDictionary *dictValues = [NSMutableDictionary dictionaryWithDictionary:@{@"xpos":@10,@"ypos":@10,@"height":@30}];
    UIButton *previousBtn;
    for (int i=0; i<20; i++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:[NSString stringWithFormat:@"%d",i+1] forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor redColor]];

        [btn setTranslatesAutoresizingMaskIntoConstraints:false];
        [sview addSubview:btn];


        if (previousBtn == nil)
        {
            [sview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[btn]-|" options:0 metrics:dictValues views:@{@"btn":btn}]];

            [sview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(ypos)-[btn(height)]" options:0 metrics:dictValues views:@{@"btn":btn}]];
        }
        else
        {
            [sview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[btn]-|" options:0 metrics:dictValues views:@{@"btn":btn}]];//Look here i set button width same as a scrollview width but not able to do that


            [sview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[previousBtn]-10-[btn(height)]" options:0 metrics:dictValues views:@{@"btn":btn,@"previousBtn":previousBtn}]];
        }

        previousBtn = btn;
    }

    NSDictionary *dictBtn = NSDictionaryOfVariableBindings(previousBtn);

    [sview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[previousBtn]-|" options:0 metrics:dictValues views:dictBtn]];

    [sview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[previousBtn(height)]-|" options:0 metrics:dictValues views:dictBtn]];

以下是此代码的屏幕截图 纵向

enter image description here

在风景中

enter image description here

查看屏幕截图按钮与文本大小相同,不像滚动视图,还有一件我使用的纯自动布局

0 个答案:

没有答案