了解宽高比约束和乘数

时间:2016-01-06 11:08:58

标签: ios uiscrollview uibutton autolayout constraints

我已经以编程方式创建了UIScrollview。我在这个滚动视图中添加了一些以编程方式创建的按钮。按钮高度为30.但按钮宽度根据屏幕大小而变化。

float scrollYearX=btnLeftArrow.frame.origin.x+btnLeftArrow.frame.size.width+15;
float scrollYearY=40.0;
float scrollYearWidth=btnRightArrow.frame.origin.x-15-scrollYearX;
float scrollYearHeight=50.0;
scrollYear=[[UIScrollView alloc] initWithFrame:CGRectMake(scrollYearX, scrollYearY, scrollYearWidth, scrollYearHeight)];

[scrollYear setShowsHorizontalScrollIndicator:NO];
[scrollYear setShowsVerticalScrollIndicator:NO];

[vwParent addSubview:scrollYear];
int buttonX=0;

for (int i=0; i<100; i++) {
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(buttonX, 0, scrollYearWidth/5, 30)];
    [btn.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:14.0]];

    int mod=i%2;
    if (mod==1) {
        [btn setTitle:@"-" forState:UIControlStateNormal];
        [btn.titleLabel setTextColor:[UIColor whiteColor]];

    }
    else
    {
        [btn addTarget:self action:@selector(yearClick :) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:[NSString stringWithFormat:@"%li",(long)backYear] forState:UIControlStateNormal];
        if (backYear==year) {
            btnCurrentYear=btn;
            [btn setBackgroundImage:[UIImage imageNamed:@"yearSelect"] forState:UIControlStateNormal];
        }
        backYear++;
    }
    [scrollYear addSubview:btn];
    btnLast=btn;
    buttonX=buttonX+btn.frame.size.width;
}
[scrollYear setContentSize:CGSizeMake(btnLast.frame.origin.x+btnLast.frame.size.width, scrollYearHeight)];
[scrollYear setContentOffset:CGPointMake(btnCurrentYear.frame.origin.x-(btnLast.frame.size.width*2),0)];

我的问题是我应该使用哪种约束来在每个设备中正确显示它。在这里,我已经附上了它在6s和ipad pro上的显示方式。如何使ipad pro与6s视觉相同。

按钮lss in 6s

enter image description here

按钮在ipad pro中查找 enter image description here

请帮帮我。 感谢

1 个答案:

答案 0 :(得分:0)

这是因为您的按钮背景宽度已缩放。你需要使用可调整大小的图像来保持圆形边缘。使用以下方式更改背景图片:

UIImage* backgroundImage = [UIImage imageNamed:@"yearSelect"];
backgroundImage = [backgroundImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backgroundImage.size.width/2-1, 0, backgroundImage.size.width/2)];
[btn setBackgroundImage:backgroundImage forState:UIControlStateNormal];