UITextView文本在应用转换后消失



我有一个简单的UITextView,在我的应用程序中有一个自定义的NSLayoutManager。UITextView有一个点击手势,当你点击UITextView时,它会离开屏幕。我的问题是当你点击UITextView时整个文本就消失了。调试一段时间后,我认为它与我传递给UITextView的NSTextContainer有关,因为如果我不传递它,一切都可以正常工作。我认为它必须对我的自定义NSLayoutManager做一些事情,但后来我用默认的NSLayoutManager测试了它,它仍然给出同样的问题。你能告诉我出了什么问题吗?我附上了一个示例代码供您参考。我放慢了动画的速度,这样可以看到哪里出错了。

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setUpTextView()
}
private func setUpTextView() {
let rect = CGRect(origin: CGPoint(x: view.frame.origin.x,
y: view.frame.origin.y + 50
),
size: CGSize(width: view.frame.width,
height: view.frame.height - 50
)
)

let textView = MyTextView(frame: rect)

textView.backgroundColor = .gray
textView.layer.cornerRadius = 15

textView.textContainerInset.left = view.frame.width * 0.05
textView.textContainerInset.right = view.frame.width * 0.05
textView.textContainerInset.top = view.frame.height * 0.05
textView.textContainerInset.bottom = view.frame.height * 0.05

let string = "The Ultimate Fighting Championship is an American mixed martial arts promotion company based in Las Vegas, Nevada."
let attributedText = NSAttributedString(string: string, attributes: [
.font: UIFont.systemFont(ofSize: 24, weight: .semibold),
.foregroundColor: UIColor.white
])

textView.attributedText = attributedText

textView.isScrollEnabled = false
textView.isEditable = false
textView.isSelectable = false

view.addSubview(textView)
}
}

MyTextView

class MyTextView: UITextView {
override init(frame: CGRect, textContainer: NSTextContainer?) {
let textStorage = NSTextStorage()
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)

let textContainer = NSTextContainer(size: frame.size)
layoutManager.addTextContainer(textContainer)

super.init(frame: frame, textContainer: textContainer)
addGesture()
}

required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

private func addGesture() {
let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
addGestureRecognizer(gesture)
}

@objc func handleTap(gesture: UITapGestureRecognizer) {
UIView.animate(withDuration: 10, delay: 0) {
self.transform = CGAffineTransform(translationX: 0, y: self.frame.height)
}
}
}

你遇到的问题是你正在将你的视图定位在屏幕外。

当UIKit生成动画时,它计算final的位置,并决定,因为您的文本视图将不再可见,它不需要呈现文本容器的内容。

如果想要继续使用转换(虽然,我建议反对,而不是使用自动布局),你可以修复你的消失的文本通过动画textView所以1点仍然在视图的边界内,然后移动它在完成块的最后一点。

像这样:

UIView.animate(withDuration: 10.0, animations: {
self.transform = CGAffineTransform(translationX: 0, y: self.frame.height - 1.0)
}, completion: { _ in
self.transform = CGAffineTransform(translationX: 0, y: self.frame.height)
})

相关内容

  • 没有找到相关文章

最新更新