事件处理程序触发但未执行UI代码(MonoTouch)

时间:2013-10-21 10:28:20

标签: c# xamarin.ios

我有一个uivewcontroller在视图加载时有事件处理程序。它包含在后台和UI中触发的代码,因此对于使用InvokeOnMainThread的UI代码。它工作正常,直到我导航到另一个控制器并返回到它。当事件触发时,它不执行UI代码。每次我推动这个控制器,我都在创建一个新的实例。所以我试图让它只有这个控制器的一个实例,它工作正常!!!!任何人都可以向我解释为什么会发生这种情况?? !!

        public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        if (hubConnection == null) {
            hubConnection = new HubConnection ("http://" + JsonRequest.IP + ":8070/", "userId=" + userId);
            hubProxy = hubConnection.CreateHubProxy ("myChatHub");
            hubConnection.EnsureReconnecting ();
            //}
            if (hubConnection.State == ConnectionState.Disconnected) {
                hubConnection.Start ();
            }
            hubConnection.Received += HandleReceived;

        }
    }

    void HandleReceived (string obj)
    {
        InvokeOnMainThread (delegate {
            discussion.Root [0].Add (new ChatBubble (true, text));

        });
    }

2 个答案:

答案 0 :(得分:2)

首先,这里不需要使用 InvokeOnMainThread ,因为 TouchUpInside 保证会在主线程上触发。

第二个问题是您的 sendButton 字段是静态的,但您的控制器实例不是。这就是为什么它只会被添加到控制器的第一个实例中。删除static关键字,它应该可以工作。

答案 1 :(得分:1)

您几乎应该永远不会使用static UI组件,这几乎总会导致问题。任何类型的UI构建通常都在LoadView方法中完成,任何类型的事件布线/视图设置都应该在ViewDidLoad中完成,例如

public class TestController : UITableViewController
{
    private UIButton sendButton;
    ...
    public override void LoadView()
    {
        base.LoadView();
        if (sendButton == null)
        {
            sendButton = new UIButton (UIButtonType.RoundedRect)
            {
                 Frame = new RectangleF (100, 100, 80, 50),
                 BackgroundColor = UIColor.Blue
            };
            View.AddSubview(sendButton);
        }
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();
        sendButton.TouchUpInside += HandleTouchUpInside;
    }

    public override void ViewDidUnload()
    {
        if (sendButton != null)
        {
            sendButton.Dispose();
            sendButton = null;
        }
    }
}

几个笔记:

  • ViewDidLoad / ViewDidUnloaddeprecated in iOS 6,因此您不再需要执行此类操作,建议您将清理代码放在DidReceiveMemoryWarning方法中。
  • 您的代码已在主循环中运行 - InvokeOnMainThread是不必要的。
相关问题