CATextLayer fontSize 上的 CABasicAnimation 不起作用

CABasicAnimation on CATextLayer fontSize not working

当用户在 UITextView 中输入的字符数超过允许的最大值时,我正在尝试在 CATextLayer 上制作脉冲动画。

代码运行但没有动画。

public partial class MyViewController : UIViewController, IUITextViewDelegate
{
   const int MAX_COMMENTS_CHARS = 500;
   CATextLayer charsLeftTextLayer;

   public override void ViewDidLoad()
   {
      base.ViewDidLoad();

      charsLeftTextLayer = new CATextLayer();
      var uiFont = UIFont.SystemFontOfSize(12);
      charsLeftTextLayer.ContentsScale = UIScreen.MainScreen.Scale; //stops text appearing blurry
      charsLeftTextLayer.SetFont(uiFont.Name);
      charsLeftTextLayer.FontSize = 12;
      charsLeftTextLayer.String = $"{MAX_COMMENTS_CHARS} chars left";
      charsLeftTextLayer.ForegroundColor = UIColor.Black.CGColor;
      charsLeftTextLayer.BackgroundColor = UIColor.Clear.CGColor;
      charsLeftTextLayer.Frame = new CGRect(582, 153, 99, 21);

      View.Layer.AddSublayer(charsLeftTextLayer);
   }

   private void PulseCharsLeft()
    {
        var animation = CABasicAnimation.FromKeyPath("fontSize");

        animation.SetFrom(NSNumber.FromNInt(12));
        animation.SetTo(NSNumber.FromNInt(16));
        animation.Duration = 1.0;
        animation.BeginTime = 0.01;
        animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
        animation.AutoReverses = true;

        charsLeftTextLayer.AddAnimation(animation, null);
    }

    #region UITextView delegates

    [Export("textView:shouldChangeTextInRange:replacementText:")]
    public bool ShouldChangeText(UITextView textView, NSRange range, string text)
    {       
        if (textView.Text.Length + text.Length > MAX_COMMENTS_CHARS)
        {
            PulseCharsLeft();
            return false;
        }

        return true;
    }

    #endregion
}

我将接受 C# 中的答案,Swift 或 Objective-C

把方法PulseCharsLeft()中的animation.BeginTime = 0.01;去掉就可以了

它应该看起来像:

private void PulseCharsLeft()
{
    var animation = CABasicAnimation.FromKeyPath("fontSize");

    animation.SetFrom(NSNumber.FromNInt(12));
    animation.SetTo(NSNumber.FromNInt(16));
    animation.Duration = 1.0;
    //animation.BeginTime = 10;
    animation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
    animation.AutoReverses = true;

    charsLeftTextLayer.AddAnimation(animation, "basic");

}

BeginTime 指定与其父动画的相对开始时间(默认情况下,一个组中的多个动画同时触发)。

来自document

Specifies the begin time of the receiver in relation to its parent object, if applicable.

您可以查看 answer here 以了解有关 BeginTime 的更多信息。

顺便说一句,在问题中,您的 charsLeftTextLayer.Frame = new CGRect(582, 153, 99, 21);x(582) 是否太大,您无法测试?

我把它改成一个小值,加个textView测试一下

    charsLeftTextLayer.Frame = new CGRect(82, 153, 99, 21);

另外我把MAX_COMMENTS_CHARS改成了10这样更容易测试。