UITextView中的中心文本无法正常工作

时间:2016-04-09 14:13:35

标签: ios objective-c uitextview

我在热门问题(Center text vertically in a UITextView

中尝试了很多解决方案

但是,当我尝试添加代码时(我的项目是Obj-C),(来自s.ka&#39的答案):

- (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)];
}

我收到以下错误:&#34;使用未声明的标识符&#39; observeValueforKeyPath&#39; &#34;

我确定这只是我犯的一个愚蠢的错误,但我无法弄明白。

侧面:看来这是以iOS 7-9为中心的最佳答案。如果它不能在iOS 7-9上工作(我只测试iOS 9设备),请告诉我。

我正在运行最新版本的XCode。

更新:我能够让错误消失(谢谢,Iman),但现在它什么也没做。文字显示,但它没有居中。如果有帮助,我的textview名为quote_text,如果这意味着我应该修改代码。两种解决方案都无效。我不知所措。

谢谢!
分支

2 个答案:

答案 0 :(得分:0)

<强>更新

我认为因为你没有使用Autolayout,无论如何 在viewDidLoad方法中使用此代码

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)];

答案 1 :(得分: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 };