根据 textview (swif3) 中的行数应用动画持续时间
Apply animation duration depending on number of lines in textview (swif3)
我在此处的代码为 textview 设置动画并向下滚动。
UIView.animate(withDuration: 10) { // 10 seconds
self.textView.contentOffset = CGPoint(x: 0, y: 225)
}
问题是现在无论文本字段中有多少行,它都遵循相同的命令。我想要做的是让动画遵循确定持续时间的线比率。例如,对于文本字段中的每 3 行,它会增加 1 秒的持续时间。因此,如果文本视图中总共有 21 行,则持续时间长度将为 7 秒。
试试这个
// Calculate number of lines according to font
var font = UIFont.boldSystemFont(ofSize: CGFloat(11.0))
var size: CGSize = string.size(with: font, constrainedToSize: textView.frame.size, lineBreakMode: .wordWrap) // default mode
var numberOfLines: Float = size.height / font.lineHeight
// 1 sec per third line
let duration = Int(numberOfLines / 3)
UIView.animate(withDuration: TimeInterval(duration)) {
self.textView.contentOffset = CGPoint(x: 0, y: 225)
}
或者您可以使用扩展程序
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.lineFragmentRectForGlyphAtIndex(
index, effectiveRange: &lineRange
)
index = NSMaxRange(lineRange)
numberOfLines += 1
}
return numberOfLines
}
}
然后计算时长
// 1 sec per third line
let duration = Int(textView.numberOfLines() / 3)
UIView.animate(withDuration: TimeInterval(duration)) {
self.textView.contentOffset = CGPoint(x: 0, y: 225)
}
我在此处的代码为 textview 设置动画并向下滚动。
UIView.animate(withDuration: 10) { // 10 seconds
self.textView.contentOffset = CGPoint(x: 0, y: 225)
}
问题是现在无论文本字段中有多少行,它都遵循相同的命令。我想要做的是让动画遵循确定持续时间的线比率。例如,对于文本字段中的每 3 行,它会增加 1 秒的持续时间。因此,如果文本视图中总共有 21 行,则持续时间长度将为 7 秒。
试试这个
// Calculate number of lines according to font
var font = UIFont.boldSystemFont(ofSize: CGFloat(11.0))
var size: CGSize = string.size(with: font, constrainedToSize: textView.frame.size, lineBreakMode: .wordWrap) // default mode
var numberOfLines: Float = size.height / font.lineHeight
// 1 sec per third line
let duration = Int(numberOfLines / 3)
UIView.animate(withDuration: TimeInterval(duration)) {
self.textView.contentOffset = CGPoint(x: 0, y: 225)
}
或者您可以使用扩展程序
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.lineFragmentRectForGlyphAtIndex(
index, effectiveRange: &lineRange
)
index = NSMaxRange(lineRange)
numberOfLines += 1
}
return numberOfLines
}
}
然后计算时长
// 1 sec per third line
let duration = Int(textView.numberOfLines() / 3)
UIView.animate(withDuration: TimeInterval(duration)) {
self.textView.contentOffset = CGPoint(x: 0, y: 225)
}