【问题标题】:Video autoplayed - ContainerView - Switching between views - Swift 3视频自动播放 - ContainerView - 在视图之间切换 - Swift 3
【发布时间】:2017-01-04 13:40:22
【问题描述】:

我有一个HMSegmentedControl 用于在段之间切换。我使用容器视图在这些片段之间切换,效果很好,但是我的一个标签有一个在viewDidAppear 上自动播放的视频。所以我的问题是,当容器视图加载之前的所有内容并根据isHidden = false 显示视图时,即使未选择该片段,我的视频也会开始播放。这种情况我该怎么办?

这是我在 segmentedControlValueChanged 事件上的代码

print("selected index \(segmentedControl.selectedSegmentIndex)")

    switch segmentedControl.selectedSegmentIndex {
    case 0:
        liveContainer.isHidden = true
    case 1:
        liveContainer.isHidden = true
    case 2:
        liveContainer.isHidden = false
    default:
        break
    }

【问题讨论】:

  • 你能把你的代码sn-p放在这里吗?
  • 你想什么时候播放视频?
  • 一旦标签/段的页面可见
  • 那你为什么要自动播放视频?只需暂停视频并在片段更改时播放。
  • 我已经编写了将其加载到 viewDidAppear 中的代码,但它只是在我点击相应的片段之前开始播放

标签: ios swift uicontainerview segmentedcontrol


【解决方案1】:

当视频显示/隐藏时,您可以使用NSNotificationCenter 向包含视频的视图控制器发送通知以播放/停止视频。这可以在容器视图段选择中完成。因此,您可以从viewDidAppear 中删除自动播放并将其添加到发送通知时调用的方法中。

例如,在您的segmentedControlValueChanged 事件中,您可以编写:

switch segmentedControl.selectedSegmentIndex {
case 0:
    liveContainer.isHidden = true
    NotificationCenter.default.post(name: Notification.Name("StopVideo"), object: nil)
case 1:
    liveContainer.isHidden = true
    NotificationCenter.default.post(name: Notification.Name("StopVideo"), object: nil)
case 2:
    liveContainer.isHidden = false
    NotificationCenter.default.post(name: Notification.Name("PlayVideo"), object: nil)
default:
    break
}

在您的视频ViewController 中,您可以有两种方法:一种用于播放视频:

func playVideo() {
  //play video here
}

另一个用于阻止它:

func stopVideo() {
  //stop video here
}

在你的视频ViewControllerviewDidLoad方法中,你可以添加观察者:

NotificationCenter.default.addObserver(self, selector: #selector(playVideo), name: "PlayVideo", object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(stopVideo), name: "StopVideo", object: nil)

【讨论】:

  • 请举个例子
【解决方案2】:

试试NSNotificationCenter

接收文件时:

-viewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"NOTIFICATIONID" object:nil];

并创建方法来接收通知。

-(void)receiveNotification:(NSNotification *) notification{
    if ([notification.name isEqualToString:@"NOTIFICATIONID"])
    {
        NSDictionary* userInfo = notification.userInfo;
        NSNumber* segmentID = (NSNumber*)userInfo[@"segmentID"];
        NSLog (@"Successfully received test notification! %i", segmentID.intValue);
    }
}

发布通知:

NSDictionary* userInfo = @{@"segmentID": @(segmentID)}; //Used to pass Objects to Notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATIONID" object:self userInfo:userInfo];

禁用您当前的自动播放。当您收到通知时,只需播放您的视频。仅在您选择细分时发布通知。

【讨论】:

  • 这两种方法都会被调用,即使我的视图被隐藏了
  • 没有。请举个例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 2017-06-20
  • 2017-10-17
  • 2020-06-27
相关资源
最近更新 更多