【问题标题】:How to send NSNotifications between tabs using UITabBarController (Swift)如何使用 UITabBarController (Swift) 在选项卡之间发送 NSNotifications
【发布时间】:2016-01-12 08:06:14
【问题描述】:

现在我有两个标签: Tab #1 有地图和固定位置。 Tab #2 有固定位置的地址。

我想要发生的是,当我删除标签 #1 上的图钉时,标签 #2 上的数据应该设置为空。但是,发生的情况是,即使我删除了 pin,该信息仍然存在于第二个选项卡上。

这是我的标签 #1 的代码:

@IBAction func trashButtonSelected(sender: AnyObject) {
        // Remove from NSDefaults
        // Show alertview
        let alertController = UIAlertController(title: "Are you Sure?", message: "Do you wish to delete your pinned Location?", preferredStyle: .ActionSheet);
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (Action) in
            // Cancel
        }
        let deleteButton = UIAlertAction(title: "Delete", style: .Destructive) { (Action) in
            NSUserDefaults.standardUserDefaults().removeObjectForKey("pinnedLocation");
            NSNotificationCenter.defaultCenter().postNotificationName("reloadData", object: nil);
            self.map.removeAnnotations(self.map.annotations);
            self.pinLocationButton.enabled = true;
        }
        alertController.addAction(deleteButton);
        alertController.addAction(cancelAction);
        self.presentViewController(alertController, animated: true, completion: nil);

所以我发送了一个名为 reloadData 的通知,它应该重置标签 #2 上的所有数据。

这是我的标签 #2 的代码:

在我的viewDidLoad 方法中,我有:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadData:", name: "reloadData", object: nil);

然后在我的选择器方法中:

func reloadData(notification:NSNotification) {
    smallMapView.removeAnnotations(smallMapView.annotations);
    smallMapView.showsUserLocation = true;
    let location = locationManager.location;
    let latitude = location!.coordinate.latitude;
    let longitude = location!.coordinate.longitude;
    let latDelta:CLLocationDegrees = 0.001;
    let longDelta:CLLocationDegrees = 0.001;

    let span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta);
    let overallLoc = CLLocationCoordinate2DMake(latitude, longitude);
    let region:MKCoordinateRegion = MKCoordinateRegionMake(overallLoc, span);
    self.smallMapView.setRegion(region, animated: true)
    completeAddressPinned = "NO ADDRESS INFO"

}

任何帮助将不胜感激!

【问题讨论】:

  • 当您首先点击第二个选项卡(运行 viewdidload 并设置观察者)然后再次点击第一个选项卡然后删除引脚时会发生什么...然后发布通知成功地? (因为现在已经添加了观察者)
  • 进入reloadData的selector方法,但是数据还是全部设置好了,没有多大意义……

标签: ios swift tabs uitabbarcontroller


【解决方案1】:

在您的选项卡#2 中:您应该在 init 方法上添加观察者,而不是在 viewDidload 方法上:

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!

 NSNotificationCenter.defaultCenter().addObserver(self,selector:#selector(self.shouldReloadFavoritPost(_:)),name:"shouldReloadFavorit",object:nil)
}

【讨论】:

    猜你喜欢
    • 2014-11-18
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2011-02-08
    • 2011-03-05
    • 1970-01-01
    相关资源
    最近更新 更多