无法从AppDelegate发布通知

时间:2018-11-04 18:49:55

标签: ios swift nsnotificationcenter notificationcenter

这是我的代码:

NotificationCenter.default.post(name: Notification.Name("isOnline"), object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(disableMarcar), name: Notification.Name("isOnline"), object: nil)

如果我从任何ViewController发布通知,则它可以工作,但是func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {中的AppDelegate.swift无法工作。

有人知道为什么吗? 我看过其他帖子,但没有一个回答我的问题。

1 个答案:

答案 0 :(得分:0)

在注册观察者之前发布通知没有任何作用,我认为这是一项功能。改为这样做:

@Override
public void start(Stage primaryStage) {
    Image image = new Image("knob.png");
    ImageView imageView = new ImageView(image);

    StackPane root = new StackPane(imageView);
    imageView.setPreserveRatio(true);
    imageView.setFitWidth(300);
    imageView.setFitHeight(300);

    Scene scene = new Scene(root, 500, 500);

    class MovedHandler implements EventHandler<MouseEvent> {

        double startX;
        double startRotate;

        @Override
        public void handle(MouseEvent event) {
            Point2D pt = imageView.localToParent(event.getX(), event.getY());
            double x = pt.getX();
            double newRotate = 3 * (x - startX) + startRotate;
            imageView.setRotate(newRotate);
        }

    }

    MovedHandler handler = new MovedHandler();
    imageView.setOnMouseDragged(handler);
    imageView.setOnMousePressed(event -> {
        Point2D pt = imageView.localToParent(event.getX(), event.getY());
        handler.startX = pt.getX();
        handler.startRotate = imageView.getRotate();
    });

    primaryStage.setScene(scene);
    primaryStage.show();
}