// // 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