IOS UIScrollView滚动内容自适应

设计思路:调整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];









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值