文本视图居中文本对齐 IOS 7

4
-(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中这样调用它。
[myTextView1 addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];

1
这是垂直对齐吗?您为什么要使用UITextView而不是UILabel?标签会免费为您完成此操作。 - SomeGuy
https://dev59.com/w3PYa4cB1Zd3GeqPfSPM?rq=1 - peko
3个回答

13
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)

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接