ios - 在 UITextView 中垂直居中 NSTextAttachment

标签 ios swift uitextview nstextattachment

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

更改自定义类中的边界(在 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

关于ios - 在 UITextView 中垂直居中 NSTextAttachment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33821693/

相关文章:

ios - 如何在UITableView中添加分页?

ios - textView :shouldChangeTextInRange:replacementText: returning NO, 但自动更正忽略?

iphone - 如何在导航栏上偏移 UIBarButtonItem 内的 UIButton 图像?

ios - 如何让 View Controller 知道它应该从服务器获取数据?

ios - 如何在 Swift 1.0 中覆盖 UIView 初始值设定项

ios - 如何偏移 MKMapView 以将坐标放在指定点下

ios - 如何在 UITextView textViewDidBeginEditing 中显示键盘后显示警报

ios - 在 UITextView 上替换属性文本时维护自定义属性

ios - 当字典在 iOS 中没有标题时如何解析 JSON?

ios - NSLayoutConstraint 将 View 固定到父 View 的底部边缘