您的位置:首页 > 产品设计 > UI/UE

IOS UIScrollView滚动内容自适应

2017-09-06 10:37 330 查看
设计思路:调整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];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息