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

来源:互联网 发布:淘宝开店如何发布商品 编辑:程序博客网 时间:2024/05/16 07:34
#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

0 0
原创粉丝点击