//// ViewController.m// UIScrollview//// Created by Zoujie on 15/5/7.// Copyright (c) 2015年 Zoujie. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController#define maxWide 1000000- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.#pragma mark text内容 NSString *demoStr = @"1919191919000000+"; [self widthForString:demoStr fontSize:18 andHeight:25];//ios6#pragma step one NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:18] forKey:NSFontAttributeName]; CGRect labelRect = [demoStr boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil]; UILabel *textLabel = [[UILabel alloc]init]; textLabel.text = demoStr; textLabel.textAlignment = NSTextAlignmentRight; textLabel.lineBreakMode = NSLineBreakByWordWrapping; textLabel.backgroundColor = [UIColor whiteColor]; NSLog(@"获取Rect方法宽度%f",labelRect.size.width); //指定用于显示的区域,scrollview取字体所占的宽度 CGRect rect = CGRectMake(0.0f, 0.0f, labelRect.size.width, labelRect.size.height); UIScrollView *Second = [[UIScrollView alloc]init]; Second.backgroundColor = [UIColor greenColor]; Second.bounces = NO; [self.view addSubview:Second]; [Second addSubview:textLabel]; #pragma step two scrollview frame Second.frame = CGRectMake(0, 200, self.view.frame.size.width-10, 35);//结构 #pragma step three 内容小于等于满屏时 if (rect.size.width<=self.view.frame.size.width-10) { [textLabel setFrame:CGRectMake(0, 5,self.view.frame.size.width-10, 25)]; Second.contentSize = CGSizeMake(self.view.frame.size.width-10, 35); } else{ [textLabel setFrame:CGRectMake(0, 5, rect.size.width, 25)]; Second.contentSize = CGSizeMake(rect.size.width, 35);#pragma step four 画布偏离值 画布大于屏幕时才需要偏离到屏幕最右方 [Second setContentOffset:CGPointMake(rect.size.width-self.view.frame.size.width+10,0) animated:YES]; } NSLog(@"画布大小 width ===== %f",rect.size.width); NSLog(@"==========================label width%f========================",textLabel.frame.size.width); NSLog(@"==========================label x====%f,画布的x=====%f",textLabel.frame.origin.x,Second.contentSize.width);}#pragma ios7之前的方法 弃用-(float) widthForString:(NSString *)value fontSize:(float)fontSize andHeight:(float)height{ CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(CGFLOAT_MAX, height) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型(lineBreakMode)可根据自己的实际情况进行设置 NSLog(@"size======width %f",sizeToFit.width); return sizeToFit.width;}#pragma 动态设置scrollview+label显示表达式#pragma 1.准确获取文字宽度#pragma 2.scrollview宽度,满屏-10#pragma 3.label添加在画布的位置,(1)画布小于等于屏幕,(2)画布大于屏幕,需设置偏离值@end