如何在UITextView中水平和垂直对齐文本?
我想要在UITextView中进行水平和垂直对齐文本。
是否有任何自定义方式?
请帮忙解决。
我想要在UITextView中进行水平和垂直对齐文本。
是否有任何自定义方式?
请帮忙解决。
这是一个使用Swift的解决方案,由于内容插入和偏移量略微改变,因此现在与以前不同。该解决方案可在Xcode 7 beta 6中使用。
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
textView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
textView.removeObserver(self, forKeyPath: "contentSize")
}
苹果已经改变了内容偏移和插入的工作方式,现在需要使用这个稍微修改过的解决方案来设置内容插入的顶部,而不是偏移量。
/// Force the text in a UITextView to always center itself.
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
let textView = object as! UITextView
var topCorrect = (textView.bounds.size.height - textView.contentSize.height * textView.zoomScale) / 2
topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect;
textView.contentInset.top = topCorrect
}
UITextView
没有内置的垂直对齐方法。但是,您可以通过更新contentOffset
来使文本垂直居中:[textView setTextAlignment:NSTextAlignmentCenter];
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[textView addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[textView removeObserver:self forKeyPath:@"contentSize"];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
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};
}
使用Swift垂直居中:
在viewDidLoad方法中:
textField.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
然后在你的视图控制器中的其他位置:
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
var topCorrect : CGFloat = (textField.frame.height - textField.contentSize.height);
topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect / 2
textField.contentOffset = CGPoint(x: 0, y: -topCorrect)
}
textField是与视图中的实际文本字段连接起来的。
当你想要改变水平和垂直对齐时,你应该提供上下文说明你的意图。
UITextview有一个容器和一个框架属性,你可以将其与另一个UITextview/Imageview等对齐。框架属性有一个原点和一个大小,你可以修改它们来对齐你的视图。
UITextview中的文本有一个称为textalignment的属性,你可以将其设置为NSTextAlignmentLeft、NSTextAlignmentJustified。建议你也可以调整容器的内容偏移量属性,但我发现调整框架更加直观。