我有一个自定义的 NSTextAttachment
类,我用它来缩放 UITextView
中的图像(基于 answer here )。这在 portrait
模式下效果很好。在 landscape
模式下,图像不会覆盖整个屏幕,我希望它们在 textview
中居中。
更改自定义类中的边界(在 attachmentBoundsForTextContainer:
中)没有任何区别(尝试同时更改 x
和 y
在界限内)。这还能如何改变?谢谢。
最佳答案
将 UITextView 的内容垂直居中。
在您的 UIViewController 的 viewWillAppear 中。
textView.addObserver(self, forKeyPath: "contentSize", options: .New, context: nil)
在您的 UIViewController 的 viewWillDisappear 中。
textView.removeObserver(self, forKeyPath: "contentSize")
在您的 UIViewController 中覆盖 observeValueForKeyPath。
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "contentSize" {
let height = textView.bounds.size.height
let contentHeight = textView.contentSize.height
let zoom = textView.zoomScale
let top = (height - contentHeight * zoom) / 2.0
textView.contentInset.top = top < 0.0 ? 0.0 : top
}
}
将 NSAttributtedString 的内容水平居中放置在 UITextView 中。
let attachment = NSTextAttachment()
let attachmentAttrString = NSAttributedString(attachment: attachment)
let result = NSMutableAttributedString(attributedString: attachmentAttrString)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center
let attrs:[String:AnyObject] = [NSParagraphStyleAttributeName: paragraphStyle]
let range = NSMakeRange(0, result.length)
result.addAttributes(attrs, range: range)
textView.attributedText = result
关于ios - 在 UITextView 中垂直居中 NSTextAttachment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33821693/