在 UITextView 中垂直居中 NSTextAttachment

Vertically center NSTextAttachment in a UITextView

我有一个自定义 NSTextAttachment class,我用它来缩放 UITextView 中的图像(基于 answer here)。这在 portrait 模式下效果很好。在 landscape 模式下,图像不会覆盖整个屏幕,我想将它们居中放置在 textview.

更改自定义 class 中的边界(在 attachmentBoundsForTextContainer: 中)没有任何区别(尝试更改边界中的 xy) .这还能如何改变?谢谢。

将 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