gpt4 book ai didi

iphone - UITextView 与底部对齐

转载 作者:行者123 更新时间:2023-12-03 18:38:18 27 4
gpt4 key购买 nike

我想知道如何设置 UITextView 以使里面的文本与底部对齐?就像,如果你开始打字,你总是会在最下面一行打字?

最佳答案

我不相信有一种内置方法可以垂直对齐 UITextView 中的文本,但您应该能够使用该控件的 contentOffset 属性UITextView 类来完成此任务。有关更多详细信息,请参阅此博文:

http://imagineric.ericd.net/2011/03/10/ios-vertical-aligning-text-in-a-uitextview/

更新:由于上面的链接似乎已失效,我使用 Wayback Machine 检索 an archived copy并粘贴了下面文章的文本。

The default and expected behavior of a UITextView (multi-line text) out of the box in iOS is to align the text top left in it’s container. That works well most of the time. However I recently had need to either center the text vertically within the control or have all the text align to the bottom of the control.

You can add an observer to the control and when it’s content size changes (text is set), fire a method. The method can then handle how the text is actually positioned in the control. If it doesn’t make sense to do the alignment, it will default to the normal behavior of the control (top vertical alignment).

Here we go:

- (void) viewDidLoad {
[textField addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
[super viewDidLoad];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *tv = object;
//Center vertical alignment
//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};

//Bottom vertical alignment
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height);
topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect);
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}

You can decide which you’d like to use, or flush the method out to take an argument for which type of vertical alignment you’d like to use. This works quite well and it would have been nice if the properties were built into the control to begin with.

If you can use it, enjoy.

关于iphone - UITextView 与底部对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7235310/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com