UITextView 单行垂直居中显示

来源:互联网 发布:报表编程软件 编辑:程序博客网 时间:2024/04/29 06:04

[textView addObserver:selfforKeyPath:@"contentSize"options:NSKeyValueObservingOptionNewcontext:nil];//也可以监听contentSize属性

//接收处理

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{

    UITextView *mTrasView = object;

    CGFloat topCorrect = ([mTrasView bounds].size.height - [mTrasView contentSize].height);

    topCorrect = (topCorrect <0.0 ?0.0 : topCorrect);

    mTrasView.contentOffset = (CGPoint){.x =0, .y = -topCorrect/2};

    textView.font = [UIFont systemFontOfSize:17];

    textView.textColor = [UIColor whiteColor];

    

    CGSize singleSize = [@"你好" sizeWithFont:[UIFontsystemFontOfSize:17]constrainedToSize:CGSizeMake(textView.frame.size.width,MAXFLOAT)];

    CGSize textSize = [mTrasView.text sizeWithFont:[UIFontsystemFontOfSize:17]constrainedToSize:CGSizeMake(textView.frame.size.width,MAXFLOAT)];

    NSInteger lines = textSize.height / singleSize.height;

    if (lines > 1) {

        textView.textAlignment = NSTextAlignmentLeft;

    }else {

        textView.textAlignment = NSTextAlignmentCenter;

    }

}

0 0
原创粉丝点击