【问题标题】:Textview Center Text Alignment IOS 7Textview中心文本对齐IOS 7
【发布时间】:2013-10-13 16:37:57
【问题描述】:
-(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];

【问题讨论】:

标签: iphone ios objective-c


【解决方案1】:
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)
    

    【讨论】:

    • 这很好用,除非内容适合一行。然后它与底部对齐。如果添加 `CGFloat topCorrect = (height - contentheight * [tv zoomScale])/2.0;`,就完美了。
    【解决方案3】:

    对于快速:

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

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 2013-01-30
      • 1970-01-01
      • 2014-02-06
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多