I have a simple UITextView with a custom NSLayoutManager in my app. The UITextView have a tap gesture and when you tap on UITextView it animates off the screen. My problem is that when you tap on the UITextView the entire text disappears. After debugging for a while I think it has something to do with NSTextContainer which I pass to the UITextView because If I don't pass it everything works fine. I thought it had to do something with my custom NSLayoutManager but then I tested it with a default NSLayoutManger and it is still giving the same issue. Can you please tell me what is going wrong? I have attached a sample code for your reference. I have slowed down the animation so can see what is wrong.
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)
}
}
}