在UITextView

时间:2015-11-20 08:00:55

标签: ios swift uitextview nstextattachment

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

更改自定义类中的边界(在attachmentBoundsForTextContainer:中)并没有什么区别(尝试更改边界中的xy)。怎么还能改变呢?感谢。

1 个答案:

答案 0 :(得分:2)

垂直居中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
    }
}

在UITextView中水平居中NSAttributtedString的内容。

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