Search code examples
c#.netmaui

Maui Toast message doesnt show correct color


I am using the package Controls.UserDialogs.Maui and when i show a toast message i want the toast to be a specific color. On Android this works fine but on iOS this doesnt work. I found one issue that shows the same problem (https://github.com/Alex-Dobrynin/Controls.UserDialogs.Maui/issues/29)

Does anyone know how to workaround this or if theres another package which i can use to show toast messages in a specific color?


Solution

  • CommunityToolkit.Maui have a Toast class but it doesn't allow us to customize the background color. Anyway, I have written a sample method to invoke a custom toast for iOS. Give this a try. Hope this helps.

     public static void ShowToast(string message, UIColor backgroundColor, UIColor textColor, nfloat padding)
        {
            var toast = new UILabel
            {
                Text = message,
                TextColor = textColor,
                BackgroundColor = backgroundColor,
                TextAlignment = UITextAlignment.Center,
                Lines = 0,
                Layer = { CornerRadius = 8, MasksToBounds = true },
                Alpha = 0,
                Font = UIFont.SystemFontOfSize(16),
                LineBreakMode = UILineBreakMode.WordWrap
            };
    
            toast.SizeToFit();
            toast.Frame = new CoreGraphics.CGRect(
                0,
                0,
                toast.IntrinsicContentSize.Width + (2 * padding),
                toast.IntrinsicContentSize.Height + (2 * padding)
            );
    
            
            var window = UIApplication.SharedApplication.KeyWindow;
            var mainView = window?.RootViewController?.View;
            if (mainView == null) return;
    
            toast.Center = new CoreGraphics.CGPoint(mainView.Frame.Width / 2, mainView.Frame.Height - 100);
            mainView.AddSubview(toast);
    
            
            UIView.Animate(0.5, () => toast.Alpha = 1, () =>
            {
                UIView.Animate(2.5, 0.5, UIViewAnimationOptions.CurveEaseOut,
                    () => toast.Alpha = 0,
                    () => toast.RemoveFromSuperview());
            });
        }