IOS UIScrollView滚动内容自适应

来源:互联网 发布:不同域名的区别 编辑:程序博客网 时间:2024/06/09 15:13

设计思路:调整contentSize即可:

本例未采用分类 ,而用子类扩展的方法,源码如下:

#import <UIKit/UIKit.h>typedef NS_ENUM(NSInteger, Oritation) {        horizontal = 1,    vertical,    };/** 解决自适应滚动 */@interface AutoLayoutScrollView : UIScrollView/** 自适应内容滚动尺寸 @param type 滚动方向 */-(void) autoContentSize:(Oritation) type;@end


.m文件为:

#import "AutoLayoutScrollView.h"@implementation AutoLayoutScrollView-(void) autoContentSize:(Oritation) type{    CGFloat width = 0;    CGFloat height= 0;        for (UIView* view in self.subviews){        height += view.frame.size.height;        width += view.frame.size.width;    }    switch (type) {                    case horizontal:{            self.contentSize = CGSizeMake(width, 0.0f);        }            break;                    case vertical:{                        self.contentSize = CGSizeMake(0.0f, height);                    }break;                    default:            break;    }    }@end


测试代码:在vc中


  AutoLayoutScrollView* scrollView = [[AutoLayoutScrollView alloc] initWithFrame:CGRectMake(20, 50, 300, 300)];    //scrollView.contentSize = CGSizeMake(300, 500);    scrollView.backgroundColor = [UIColor grayColor];    [self.view addSubview:scrollView];            for(int i=0;i<7;i++){                UILabel* test = [[UILabel alloc] initWithFrame:CGRectMake(0, 40 * i, 100, 50)];        test.text = [NSString stringWithFormat:@"test:%d",i];        [scrollView addSubview:test];    }    [scrollView autoContentSize:vertical];









原创粉丝点击