您的位置:首页 > 其它

设置textView根据输入的文字自动增加高度

2014-11-24 19:57 375 查看
#import "CWViewController.h"

@interface CWViewController ()<UITextViewDelegate>

@end

@implementation CWViewController

- (void)viewDidLoad
{
[super viewDidLoad];
//设置代理对象
self.textView.delegate=self;
//初始化textView的文字
self.textView.text=@"1";

self.textView.backgroundColor=[UIColor orangeColor];

// Do any additional setup after loading the view, typically from a nib.
}
- (void)textViewDidChange:(UITextView *)textView{

NSLog(@"654");
//执行方法
CGSize tempSize = [self sizeWithText:textView.text boundingRectWithSize:CGSizeMake(textView.frame.size.width, 10000000) font:textView.font];
//改变frame
textView.frame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width, tempSize.height);

}

-(CGSize)sizeWithText:(NSString *)text boundingRectWithSize:(CGSize)boundingSize font:(UIFont *)font
{
//段落
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStyle setLineSpacing:5];
//根据输入的文字字体大小设置自动高度
NSDictionary *attributes = [NSDictionary dictionaryWithObjects:@[font,paragraphStyle] forKeys:@[NSFontAttributeName,NSParagraphStyleAttributeName]];
CGSize contentSize = [text boundingRectWithSize:boundingSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;

return contentSize;
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: