Animating UILabel Font Size Change

前端 未结 9 2095
醉话见心
醉话见心 2020-11-30 21:31

I am currently making an application that uses a custom View Controller container. Multiple views are on the screen at one time and when one is tapped, the selected view con

9条回答
  •  孤街浪徒
    2020-11-30 21:34

    If you want to animate the text size from another anchor point, here is the Swift 5 solution:

    How to apply:

    yourLabel.setAnimatedFont(.systemFont(ofSize: 48), duration: 0.2, anchorPointX: 0, anchorPointY: 1)
    

    Extensions:

    extension UILabel {
      /// Animate font size from a given anchor point of the label.
      /// - Parameters:
      ///   - duration: Animation measured in seconds
      ///   - anchorPointX: 0 = left, 0.5 = center, 1 = right
      ///   - anchorPointY: 0 = top, 0.5 = center, 1 = bottom
      func setAnimatedFont(_ font: UIFont, duration: TimeInterval, anchorPointX: CGFloat, anchorPointY: CGFloat) {
        guard let oldFont = self.font else { return }
    
        setAnchorPoint(CGPoint(x: anchorPointX, y: anchorPointY))
        self.font = font
    
        let scaleFactor = oldFont.pointSize / font.pointSize
        let oldTransform = transform
        transform = transform.scaledBy(x: scaleFactor, y: scaleFactor)
        setNeedsUpdateConstraints()
    
        UIView.animate(withDuration: duration) {
          self.transform = oldTransform
          self.layoutIfNeeded()
        }
      }
    }
    
    extension UIView {
      /// Change the anchor point without moving the view's position.
      /// - Parameters:
      ///   - point: The layer's bounds rectangle.
      func setAnchorPoint(_ point: CGPoint) {
        let oldOrigin = frame.origin
        layer.anchorPoint = point
        let newOrigin = frame.origin
    
        let translation = CGPoint(x: newOrigin.x - oldOrigin.x, y: newOrigin.y - oldOrigin.y)
        translatesAutoresizingMaskIntoConstraints = true
        center = CGPoint(x: center.x - translation.x, y: center.y - translation.y)
      }
    }
    

提交回复
热议问题