我的代码基本上是一个提词器,问题是当代码大约10行时,提词器工作正常,但是当添加20行时,顶行被切断。见图 现在应用此代码动画,前4行被截断。
extension UITextView {
func numberOfLines() -> Int {
let layoutManager = self.layoutManager
let numberOfGlyphs = layoutManager.numberOfGlyphs
var lineRange: NSRange = NSMakeRange(0, 1)
var index = 0
var numberOfLines = 0
while index < numberOfGlyphs {
layoutManager.lineFragmentRect(
forGlyphAt: index, effectiveRange: &lineRange
)
index = NSMaxRange(lineRange)
numberOfLines += 1
}
return numberOfLines
}
}
import UIKit
var yPosLabel : CGFloat!
var xPosLabel : CGFloat!
class ViewController: UIViewController {
@IBOutlet var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
yPosLabel = self.textView.frame.origin.y
xPosLabel = self.textView.frame.origin.x
}
func textViewDidBeginEditing(textView: UITextView) {
if textView.textColor == UIColor.black {
textView.text = nil
textView.textColor = UIColor.black
}
}
func textViewDidEndEditing(textView: UITextView) {
if textView.text.isEmpty {
textView.text = ""
textView.textColor = UIColor.black
}
}
@IBAction func play(_ sender: Any) {
let duration = Double(textView.numberOfLines() / 2)
UIView.animate(withDuration: TimeInterval(duration)) {
let contentSize = self.textView.contentSize
let contentInset = self.textView.contentInset
let textViewBounds = self.textView.bounds
let newContentOffset = CGPoint(
x: contentSize.width + contentInset.right - textViewBounds.width,
y: contentSize.height + contentInset.bottom - textViewBounds.height
)
self.textView.contentOffset = newContentOffset
}
}}