添加一个能够自适应字数的UILabel对象到ScrollView

来源:互联网 发布:ping ip加端口 编辑:程序博客网 时间:2024/03/28 18:03
    NSString * value = _currentBook.content;    UILabel * aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];//设置初始大小    aLabel.text = value;    [aLabel setNumberOfLines:0];    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {        NSAttributedString *att = [[NSAttributedString alloc] initWithString:aLabel.text attributes:@{NSFontAttributeName: aLabel.font}];        CGRect rect = [att boundingRectWithSize:CGSizeMake(320, 100000) options:NSStringDrawingUsesLineFragmentOrigin context:NULL];//获取aLabel内容大小        [aLabel setFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)]; //修改frame大小    }else{        CGSize size = [value sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(320, 1000000)];//兼容7.0之前版本 调用方法        [aLabel setFrame:CGRectMake(0, 0, size.width, size.height)];    }    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, 320, self.view.bounds.size.height-100-64)];    [scroll setContentSize:CGSizeMake(aLabel.frame.size.width, aLabel.frame.size.height)];    [scroll addSubview:aLabel];        [self.view addSubview:scroll];    [scroll release];    [aLabel release];

0 0
原创粉丝点击