当前位置: 代码迷 >> Android >> iPhone中的Android Toast?
  详细解决方案

iPhone中的Android Toast?

热度:109   发布时间:2023-08-04 10:39:33.0

当我编写Android应用程序时,我喜欢Toast功能。 有没有办法在使用MonoTouch(C#.NET)的iPhone开发中获得这种设置并忘记弹出消息?

MonoTouch Toast版本在这里。 受到Android的启发。

打电话给

        ToastView t = new ToastView ("Email Sent", 1000);
        t.Show ();

枚举文件:

public enum ToastGravity
{
    Top = 0,
    Bottom = 1,
    Center = 2
}

ToastSettings文件:

using System;
using System.Drawing;
using MonoTouch.UIKit;
namespace General
{

    public class ToastSettings
    {
        public ToastSettings ()
        {
            this.Duration = 500;
            this.Gravity = ToastGravity.Center;
        }

        public int Duration
        {
            get;
            set;
        }

        public double DurationSeconds
        {
            get { return (double) Duration/1000 ;}

        }

        public ToastGravity Gravity
        {
            get;
            set;
        }

        public PointF Position
        {
            get;
            set;
        }


    }
}

主要吐司类:

using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.ObjCRuntime;

namespace General
{
    public class ToastView : NSObject
    {

        ToastSettings theSettings = new ToastSettings ();

        private string text = null;
        UIView view;
        public ToastView (string Text, int durationMilliseonds)
        {
            text = Text;
            theSettings.Duration = durationMilliseonds;
        }

        int offsetLeft = 0;
        int offsetTop = 0;
        public ToastView SetGravity (ToastGravity gravity, int OffSetLeft, int OffSetTop)
        {
            theSettings.Gravity = gravity;
            offsetLeft = OffSetLeft;
            offsetTop = OffSetTop;
            return this;
        }

        public ToastView SetPosition (PointF Position)
        {
            theSettings.Position = Position;
            return this;
        }

        public void Show ()
        {
            UIButton v = UIButton.FromType (UIButtonType.Custom);
            view = v;

            UIFont font = UIFont.SystemFontOfSize (16);
            SizeF textSize = view.StringSize (text, font, new SizeF (280, 60));

            UILabel label = new UILabel (new RectangleF (0, 0, textSize.Width + 5, textSize.Height + 5));
            label.BackgroundColor = UIColor.Clear;
            label.TextColor = UIColor.White;
            label.Font = font;
            label.Text = text;
            label.Lines = 0;
            label.ShadowColor = UIColor.DarkGray;
            label.ShadowOffset = new SizeF (1, 1);


            v.Frame = new RectangleF (0, 0, textSize.Width + 10, textSize.Height + 10);
            label.Center = new PointF (v.Frame.Size.Width / 2, v.Frame.Height / 2);
            v.AddSubview (label);

            v.BackgroundColor = UIColor.FromRGBA (0, 0, 0, 0.7f);
            v.Layer.CornerRadius = 5;

            UIWindow window = UIApplication.SharedApplication.Windows[0];

            PointF point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height / 2);

            if (theSettings.Gravity == ToastGravity.Top)
            {
                point = new PointF (window.Frame.Size.Width / 2, 45);
            }
            else if (theSettings.Gravity == ToastGravity.Bottom)
            {
                point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height - 45);
            }
            else if (theSettings.Gravity == ToastGravity.Center)
            {
                point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height / 2);
            }
            else
            {
                point = theSettings.Position;
            }

            point = new PointF (point.X + offsetLeft, point.Y + offsetTop);
            v.Center = point;
            window.AddSubview (v);
            v.AllTouchEvents += delegate { HideToast (null); };

            NSTimer.CreateScheduledTimer (theSettings.DurationSeconds, HideToast);

        }


        void HideToast ()
        {
            UIView.BeginAnimations ("");
            view.Alpha = 0;
            UIView.CommitAnimations ();
        }

        void RemoveToast ()
        {
            view.RemoveFromSuperview ();
        }

    }
}

看一下这个:

编辑:项目已移至github所以我更新链接。

这是我的版本: :

我认为使用它更简单,因为它是作为obj-c类实现的,因此将makeToast方法添加到任何UIView实例中。 例如:

[self.view makeToast:@"This is some message as toast."
            duration:3.0
            position:@"bottom"];

你在寻找像UIAlertView这样的东西吗?

您可以将此链接用于Toast的objective-c代码

虽然这个链接用于它的用途

这可能像下面任何一个样本

[[iToast makeText:NSLocalizedString(@"The activity has been successfully saved.", @"")] show];

[[[iToast makeText:NSLocalizedString(@"The activity has been successfully saved.", @"")] 
                          setGravity:iToastGravityBottom] show];

[[[[iToast makeText:NSLocalizedString(@"Something to display a very long time", @"")] 
                  etGravity:iToastGravityBottom] setDuration:iToastDurationLong] show];

只是你可以使用uilabel和uianimation的以下代码来获得像android一样的吐司。 它做了两个工作,一个是吐司任务,它增加了标签的高度,根据文本长度与wordwrap IOS 7稍后

CGRect initialFrame = CGRectMake(20, self.view.frame.size.height/2,300, 40);


NSString *message=@"Toast in Iphone as in Android";
UILabel *flashLabel=[[UILabel alloc] initWithFrame:initialFrame];
flashLabel.font=[UIFont fontWithName:@"Optima-Italic" size:12.0];
flashLabel.backgroundColor=[UIColor whiteColor];
flashLabel.layer.cornerRadius=3.0f;
flashLabel.numberOfLines=0;
flashLabel.textAlignment=NSTextAlignmentCenter;

CGSize maxSize = CGSizeMake(flashLabel.frame.size.width, MAXFLOAT);

CGRect labelRect = [message boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:flashLabel.font} context:nil];

//adjust the label the the new height.
CGRect newFrame = flashLabel.frame;
newFrame.size.height = labelRect.size.height;
flashLabel.frame = newFrame;
flashLabel.text=message;
[self.view addSubview:flashLabel];

flashLabel.alpha=1.0;
self.view.userInteractionEnabled=FALSE;

[UIView animateWithDuration:13.0 animations:^
{
    flashLabel.alpha=0.0f;
}
completion:^(BOOL finished)
{
    self.view.userInteractionEnabled=TRUE;

    [flashLabel removeFromSuperview];
}];

我修改了John的答案如下:

Toast.h

@interface Toast : NSObject

+ (void)toast:(NSString *)message
             :(UIView *) view
             :(int)delay;

@end

Toast.m

#import "Toast.h"

@interface Toast ()

@end

@implementation Toast

+ (void)toast:(NSString *)message
             :(UIView *) view
             :(int)delay
{
    CGRect initialFrame = CGRectMake(10, view.frame.size.height/2, 300, 40);
    UILabel *flashLabel=[[UILabel alloc] initWithFrame:initialFrame];
    flashLabel.font=[UIFont fontWithName:@"Optima-Italic" size:19.0];
    flashLabel.backgroundColor=[UIColor whiteColor];
    flashLabel.layer.cornerRadius=9.0f;
    flashLabel.clipsToBounds = YES;
    flashLabel.numberOfLines=3;
    flashLabel.textAlignment=NSTextAlignmentCenter;
    CGSize maxSize = CGSizeMake(flashLabel.frame.size.width, MAXFLOAT);
    CGRect labelRect = [message boundingRectWithSize:maxSize
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                          attributes:@{NSFontAttributeName:flashLabel.font}
                                             context:nil];

    //adjust the label the the new height.
    CGRect newFrame = flashLabel.frame;
    newFrame.size.height = labelRect.size.height * 2;
    flashLabel.frame = newFrame;
    flashLabel.text=message;
    [view addSubview:flashLabel];
    flashLabel.alpha=1.0;
    view.userInteractionEnabled=FALSE;

    [UIView animateWithDuration:delay animations:^
    {
        flashLabel.alpha=0.0f;
    }

    completion:^(BOOL finished)
    {
        view.userInteractionEnabled=TRUE;
        [flashLabel removeFromSuperview];
    }];
}

@end

您可能会在本地通知之后,非常确定它们允许您设置时间,我认为在大纪元时间被解雇。 不要以为有办法隐藏它们。 我可能会误解你的问题,因为我不熟悉Toast。

我在toast类中添加了一些修改来处理显示的旋转。

        public void Show ()
    {
        UIButton v = UIButton.FromType (UIButtonType.Custom);
        view = v;


        UIFont font = UIFont.SystemFontOfSize (16);
        SizeF textSize = view.StringSize (text, font, new SizeF (280, 60));

        UILabel label = new UILabel (new RectangleF (0, 0, textSize.Width + 5, textSize.Height + 5));
        label.BackgroundColor = UIColor.Clear;
        label.TextColor = UIColor.White;
        label.Font = font;
        label.Text = text;
        label.Lines = 0;
        label.ShadowColor = UIColor.DarkGray;
        label.ShadowOffset = new SizeF (1, 1);


        v.Frame = new RectangleF (0, 0, textSize.Width + 10, textSize.Height + 10);
        label.Center = new PointF (v.Frame.Size.Width / 2, v.Frame.Height / 2);
        v.AddSubview (label);

        v.BackgroundColor = UIColor.FromRGBA (0, 0, 0, 0.7f);
        v.Layer.CornerRadius = 5;

        UIWindow window = UIApplication.SharedApplication.Windows[0];

        PointF point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height / 2);

        if (theSettings.Gravity == ToastGravity.Top)
        {
            point = new PointF (window.Frame.Size.Width / 2, 45);
        }
        else if (theSettings.Gravity == ToastGravity.Bottom)
        {
            point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height - 45);
        }
        else if (theSettings.Gravity == ToastGravity.Center)
        {
            point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height / 2);
        }
        else
        {
            point = theSettings.Position;
        }

        point = new PointF (point.X + offsetLeft, point.Y + offsetTop);
        v.Center = point;
        //handle screen rotation
        float orientation=0;

        switch(UIApplication.SharedApplication.StatusBarOrientation)
        {
        case UIInterfaceOrientation.LandscapeLeft:
            orientation=-90;
            break;
        case UIInterfaceOrientation.LandscapeRight:
            orientation=90;
            break;
        case UIInterfaceOrientation.PortraitUpsideDown:
            orientation=180;
            break;
        }
        v.Transform=CGAffineTransform.MakeRotation ((float)(orientation / 180f * Math.Pi));
        window.AddSubview (v);
        v.AllTouchEvents += delegate { HideToast (); };

        NSTimer.CreateScheduledTimer (theSettings.DurationSeconds, HideToast);

    }

您可以尝试我的开源库TSMessages: :

它非常易于使用,在iOS 5/6和iOS 7上也很漂亮。

我非常喜欢Bahai提出的MonoTouch解决方案。

以下不是替代品。 对我来说,这只是一种随时可用的方法。

    private async Task ShowToast(string message, UIAlertView toast = null)
    {
        if (null == toast)
        {
            toast = new UIAlertView(null, message, null, null, null);
            toast.Show();
            await Task.Delay(2000);
            await ShowToast(message, toast);
            return;
        }

        UIView.BeginAnimations("");
        toast.Alpha = 0;
        UIView.CommitAnimations();
        toast.DismissWithClickedButtonIndex(0, true);
    }

如果从后台线程(而不是主UI线程)调用该方法,则需要BeginInvokeOnMainThread,这意味着只需像这样调用它。

BeginInvokeOnMainThread(() =>
{
 ShowToast(message);
});

我在github上用一个类创建了一个新的repo来做iOS toast风格的警报。 我不喜欢code.google.com上的那个,它没有正确旋转而且不漂亮。

享受乡亲。

  相关解决方案