6

概括:

在 iOS 6 中,我通过键值观察文本视图的 contentSize 属性 ( https://stackoverflow.com/a/12591299/1239263 ) 在 UITextView 中垂直居中文本。当我升级到 iOS 7 时,后一种技术的工作不一致。

与其尝试修复 KVO 技术,我更愿意使用 Text Kit 在 UITextView 中垂直居中文本。

我使用 Text Kit 设计了一个解决方案,但它会在设备旋转时中断。

UITextView 是橙色的。

当文本视图最初加载时,文本正确居中:

在此处输入图像描述

当设备旋转到横向时,文本仍然正确居中:

在此处输入图像描述

但是,当设备旋转回纵向时,文本未正确居中。文本应该在一行,就像上面的第一个屏幕截图一样。

在此处输入图像描述

对于后一个屏幕截图,将几何图形记录到控制台会显示文本视图的文本容器宽度太窄。

细节:

@interface ViewController ()

// text view is created in storyboard; it's added to the root view and it's using auto layout
@property (weak, nonatomic) IBOutlet UITextView *textView;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSTextContainer *textContainer = self.textView.textContainer;
   [textContainer setWidthTracksTextView:YES];  
}

- (void)centerText
{
    NSTextContainer *container = self.textView.textContainer;
    NSLayoutManager *layoutManager = container.layoutManager;

    CGRect textRect = [layoutManager usedRectForTextContainer:container];

    UIEdgeInsets inset = UIEdgeInsetsZero;
    inset.top = self.textView.bounds.size.height / 2 - textRect.size.height / 2;
    inset.left = self.textView.bounds.size.width / 2 - textRect.size.width / 2;

    self.textView.textContainerInset = inset;
}

- (void)viewDidLayoutSubviews
{
    [self centerText];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];

    [self centerText];
}

我试过的:

我尝试在 centerText 方法中手动设置容器大小。根据我为容器大小设置的值,在某些情况下设置容器大小确实有效。哪些情况?这取决于显示的文本行数。

// fixes problem if a single line of text; clips multi-line text
container.size = CGSizeZero; 

// fixes problem if multi-line text, but not if a single line of text
container.size = CGSizeMake(self.textView.bounds.size.width, FLT_MAX);

由于我将 widthTracksTextView 设置为 YES,我不明白为什么我需要设置文本容器大小。如果我确实需要设置文本容器宽度,为什么正确的值似乎取决于显示的行数?

4

1 回答 1

0

我想我找到了解释和解决方案。容器本身存在一些线条碎片问题。这是我在包裹里看到的。

返回providedRect的接收器内的线片段矩形的边界。这是proposedRect 和-size 属性定义的接收方边界矩形的交集。-exclusionPaths 属性定义的区域从返回值中排除。charIndex 是正在处理的行片段在文本存储中的字符位置。由于排除路径,proposedRect 可能会被分成多个行片段。

当您使用屏幕旋转时,排除路径被排除。因此文本无法保存您想要的方向值。这就是为什么当您定义 CGRect 时,它以某种方式解决了问题。所以你应该使用的方法是:

- (CGRect)lineFragmentRectForProposedRect:(CGRect)proposedRect atIndex:(NSUInteger)characterIndex writingDirection:(NSWritingDirection)baseWritingDirection remainingRect:(CGRect *)remainingRect;
于 2015-08-27T14:22:48.740 回答