0

我有一个 uivewcontroller,它在视图加载时具有事件处理程序。它包含在后台和 UI 中触发的代码,因此对于 UI 代码,我使用 InvokeOnMainThread。它工作正常,直到我导航到另一个控制器并返回它。当事件触发时,它不会执行 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));

        });
    }
4

2 回答 2

2

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

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

于 2013-10-21T11:39:05.000 回答
1

你应该,几乎总是,永远不要使用staticUI 组件,这几乎总是会导致问题。任何类型的 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/在 iOS 6 中已弃用,ViewDidUnload因此您不再需要执行此类操作,建议您将清理代码放在方法中。DidReceiveMemoryWarning
  • 您的代码已经在主循环中运行 -InvokeOnMainThread是不必要的。
于 2013-10-21T11:42:27.100 回答