且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式在 UIScrollView 中使用 AutoLayout 设置子视图?

更新时间:2021-10-23 07:14:20

Here is a SO answer 解释了如何使用自动布局做到这一点,他已经完美地解释了,这里有垂直文本字段,但在你的情况下,你必须设置水平视图约束.

Here is a SO answer has explained how to do this with auto layout, he has explain perfectly , In here there is vertically textfields are there But in your case it is you have to set Horizontal views constraints.

替代方案

设置约束你可以只设置子视图的框架并在滚动视图中设置它,并且基于方向你可以改变滚动视图的子视图的框架.

Rather that setting constraints you can set just frame of the subview and set it in Scrollview, And based on orientation you can change frames of the scrolview's subviews.

你的 setData 方法比如,

Your setData Method like,

-(void)setData{

    [self layoutIfNeeded];
    CGRect mainFrame=scrollView.frame;
    CGRect frame;
    for (int i=0; i<arrayData.count ; i++)
    {
        CGRect frame;
        frame.origin.x = scrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.size = scrollView.frame.size;

        frame.origin=CGPointMake(0, 0);
        UIView *subview = [[UIView alloc]initWithFrame:frame];
        subview.backgroundColor = [self getRandomColor];
        [scrollView addSubview:subview];
    }
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * arrayData.count, mainFrame.size.height/2);
}

现在你使用 NSNotificationCenter 可以在设备方向改变时得到通知,所以在它的这个选择器方法中调用你的 setData 方法,

Now you using NSNotificationCenter you can get notify when device orientation chaged, so in this selector method of it call your setData method,

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(setData)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];

现在在您的 setData 方法中,您需要删除所有子视图,因为当设备更改方向时,它将向您的滚动视图添加新视图,因此在设置其框架之前从 Scrollview 中删除所有子视图,

Now in you setData method you need remove all subviews because when device changes Orientation it will add new views to your scrollview, so remove all subview from Scrollview before setting its frame,

        [scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

确保您正在从班级中移除观察者,例如,

Make sure you are removing observer from your class like,

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}