CATextLayer fontSize上的CABasicAnimation无法正常工作

时间:2019-05-30 13:35:19

标签: xamarin xamarin.ios cabasicanimation

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

代码会运行,但动画不会发生。

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的答案

1 个答案:

答案 0 :(得分:2)

删除方法animation.BeginTime = 0.01;中的PulseCharsLeft(),然后它将起作用。

它应该像这样:

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

  

指定接收者相对于其父对象的开始时间   对象(如果适用)。

您可以查看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,更易于测试。

相关问题