iOS 7 UITextView vertical alignment

前端 未结 8 715
不思量自难忘°
不思量自难忘° 2020-11-29 04:21

How is that possible that my editable UITextView (placed inside a straightforward UIViewController inside a UISplitView that acts as delegate for t

8条回答
  •  半阙折子戏
    2020-11-29 05:19

    This is a fairly common problem, so I would create a simple UITextView subclass, so that you can re-use it and use it in IB.

    I would used the contentInset instead, making sure to gracefully handle the case where the contentSize is larger than the bounds of the textView

    @interface BSVerticallyCenteredTextView : UITextView
    
    @end
    
    @implementation BSVerticallyCenteredTextView
    
    - (id)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame])
        {
            [self addObserver:self forKeyPath:@"contentSize" options:  (NSKeyValueObservingOptionNew) context:NULL];
        }
        return self;
    }
    
    - (id)initWithCoder:(NSCoder *)aDecoder
    {
        if (self = [super initWithCoder:aDecoder])
        {
            [self addObserver:self forKeyPath:@"contentSize" options:  (NSKeyValueObservingOptionNew) context:NULL];
        }
        return self;
    }
    
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if ([keyPath isEqualToString:@"contentSize"])
        {
            UITextView *tv = object;
            CGFloat deadSpace = ([tv bounds].size.height - [tv contentSize].height);
            CGFloat inset = MAX(0, deadSpace/2.0);
            tv.contentInset = UIEdgeInsetsMake(inset, tv.contentInset.left, inset, tv.contentInset.right);
        }  
    }
    
    - (void)dealloc
    {
        [self removeObserver:self forKeyPath:@"contentSize"];
    }
    
    @end
    

提交回复
热议问题