简体   繁体   中英

Center Text Vertically in UITextView not working

I've tried many of the solutions in the popular question ( Center text vertically in a UITextView )

However, when I try to add the code (my projecr is Obj-C), (from s.ka's answer):

- (void) viewDidLoad {
     [textField addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
     [super viewDidLoad];
}


    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    UITextView *tv = object;
    CGFloat topCorrect = ([tv bounds].size.height - [tv     contentSize].height * [tv zoomScale])/2.0;
    topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
    [tv setContentInset:UIEdgeInsetsMake(topCorrect,0,0,0)];
}

I get the following error: "use of undeclared identifier 'observeValueforKeyPath' "

I'm sure it's just a stupid error I'm making, but I can't figure it out.

On the side: It appears this is the best answer for centering text iOS 7-9. If it won't work on iOS 7-9 (I only have iOS 9 devices to test with), let me know.

I'm running the latest version of XCode.

Update: I was able to get the error to go away (thanks, Iman) but now it just doesn't do anything. Text shows, but it's not centered. If it helps, my textview is named quote_text, if that means I should revise the code. Neither solution works. I'm at a loss.

Thanks!
Branch

UPDATE

i think because you are not using Autolayout, Anyhow use this code in your viewDidLoad method

CGFloat topCorrect = ([quote_text bounds].size.height - [quote_text contentSize].height * [quote_text zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
[quote_text setContentInset:UIEdgeInsetsMake(topCorrect,0,0,0)];
     [self.yourTextView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:NULL];

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

         {
           UITextView *tv = object;
           CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * tv.zoomScale) / 2.0;
           if (topCorrect < 0) {
                 topCorrect = 0.0;
         }
     tv.contentOffset = (CGPoint) { .x = 0, .y = -topCorrect };



The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM