根据textview(swif3)中的行数应用动画持续时间

时间:2017-06-24 20:37:25

标签: ios animation swift3 textview lines

我的代码在这里为textview设置动画并向下滚动。

        UIView.animate(withDuration: 10) { // 10 seconds
        self.textView.contentOffset = CGPoint(x: 0, y: 225)
    }

问题是它遵循相同的命令,现在文本字段中有多少行。我想要做的是让动画遵循线比率,确定持续时间的长度。例如,对于文本字段中的每3行,它的持续时间增加1秒。因此,如果textview中总共有21行,则持续时间长度将为7秒。

1 个答案:

答案 0 :(得分:0)

试试这个

    // 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)
    }