2013-10-07 121 views
3
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{ 
    NSLog(@"Hello"); 
    UITextView *tv = object; 
    CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0; 
    topCorrect = (topCorrect < 0.0 ? 0.0 : topCorrect); 
    tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect}; 
} 

我打电话像这样在viewDidLoad中的TextView中心文本对齐IOS 7

[myTextView1 addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL]; 
+1

这是垂直对齐?是否有任何理由通过UILabel使用UITextView?该标签将为您免费提供此功能。 – SomeGuy

+0

http://stackoverflow.com/questions/17024375/uitextview-alligining-text-vertically-center?rq=1 – peko

回答

11
textView.textAlignment = NSTextAlignmentCenter; 
2

试试这iOS7:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
    { 
UITextView *tv = object; 

CGFloat height = [tv bounds].size.height; 
CGFloat contentheight; 

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) { 
    contentheight = [tv sizeThatFits:CGSizeMake(tv.frame.size.width, FLT_MAX)].height; 
    NSLog(@"iOS7; %f %f", height, contentheight); 
}else{ 
    contentheight = [tv contentSize].height; 
    NSLog(@"iOS6; %f %f", height, contentheight); 
} 

CGFloat topCorrect = height - contentheight; 
topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect); 
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect}; 
} 

被定义为:

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) 
+2

这个工程很好,除了当内容适合一行。然后它将它与底部对齐。如果你添加'CGFloat topCorrect =(height - contentheight * [tv zoomScale])/ 2.0;',它可以完美地工作。 – barndog

0

对于SWIFT:

 itemTextView.addObserver(self, forKeyPath:"contentSize", options: NSKeyValueObservingOptions.New, context: nil) 

override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) { 
    var tv : UITextView = object as UITextView; 
    var height = tv.bounds.size.height; 
    var contentheight = tv.sizeThatFits(CGSizeMake(tv.frame.size.width,1000)).height 


    var topCorrect : CGFloat = height - contentheight; 
    if(topCorrect < 0) { 
     topCorrect = 0 
    } 
    tv.contentOffset = CGPointMake(0, -topCorrect/2) 

}