首页 > 解决方案 > 我想从另一个 ViewController 调用我的函数

问题描述

我有一个scrollView,里面有一个textView,有一个功能可以在我的主vc中滑动我的scrollView(带动画)我还有一个按钮(在黑色圆圈内),当我按下它时,我的弹出视图控制器打开然后我在我的函数中选择一个动画延迟值。当我按下我的播放按钮(在红色圆圈内)时,我想关闭我的弹出 vc 并且我希望我的函数运行。看:

func startScrollSlideShow(sliderValue: Float) {
    
    if (scrollView.contentOffset.y <= (scrollView.contentSize.height - scrollView.frame.size.height)){
        //reach bottom
        
        UIScrollView.animate(withDuration: TimeInterval(sliderValue), delay: 0.5, options: .allowAnimatedContent, animations: {
            self.scrollView.contentOffset.y += 3.5
        }) { (completion) in
            
            self.startScrollSlideShow(sliderValue: Float(UserDefaults.standard.string(forKey: "sliderValue")!)!)
        }
    } else {           
        return
    }        
}

@objc func scrollTextView(){
    
    self.present(SliderViewController(title: "Otomatik Kaydırma"), animated: true, completion: nil)
    
//    self.startScrollSlideShow(sliderValue: Float(UserDefaults.standard.string(forKey: "sliderValue")!)!)
}

这些在我的主 vc 中,而不是我的弹出 vc 中。

标签: iosswiftxcode

解决方案


您可以为此使用委托模式:

protocol PlayViewDelegate: class {
    func playButtonPressed()
}

// Implement the protocol in your Main VC
extension MainViewController: PlayViewDelegate {
    func playButtonPressed() {
        // Play
    }
}

// Add delegate to the alert like VC
class PlayViewController: UIViewController {
    weak var delegate: PlayViewDelegate?
    
    @IBAction
    func playPressed() {
        self.delegate?.playButtonPressed()
        self.dismiss(animated: true, completion: nil)
    }
}

推荐阅读