[英]Vertically center NSTextAttachment in a UITextView
I have an custom NSTextAttachment
class which I use to scale images inside a UITextView
(based on the answer here ). 我有一个自定义的NSTextAttachment
类,该类用于缩放UITextView
图像(基于此处的答案 )。 This works great in portrait
mode. 这在portrait
模式下效果很好。 In landscape
mode, the images do not cover the whole screen and I want to center them in the textview
. 在landscape
模式下,图像不能覆盖整个屏幕,我想将它们居中在textview
。
Making changes to the bounds in the custom class (in attachmentBoundsForTextContainer:
) does not make a difference (tried changing both x
and y
in the bounds). 更改自定义类中的界限(在attachmentBoundsForTextContainer:
)不会有所不同(尝试更改界限中的x
和y
)。 How else can this be changed? 还有什么可以改变的呢? Thanks. 谢谢。
Vertically center the content of a UITextView. 将UITextView的内容垂直居中。
In viewWillAppear of your UIViewController. 在您的UIViewController的viewWillAppear中。
textView.addObserver(self, forKeyPath: "contentSize", options: .New, context: nil)
In viewWillDisappear of your UIViewController. 在您的UIViewController的viewWillDisappear中。
textView.removeObserver(self, forKeyPath: "contentSize")
Override observeValueForKeyPath in your UIViewController. 覆盖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
}
}
Horizontally center the content of an NSAttributtedString inside a UITextView. 将UIAtView中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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.