2017-04-24 52 views
1

在一個iOS項目中,我有一個主ViewController和第二個ViewController,第二個ViewController在導航欄中顯示爲一個帶有從一個按鈕的segue的Popover。在這種酥料餅沒有與此代碼的按鈕:如何從Popover調用主視圖控制器的方法?

class Pop: UIViewController { 

    @IBAction func colorOnePressed(_ sender: Any) { 
     let vc = ViewController() 
     vc. zoomIn() 
    } 

} 

這是第一個視圖控制器的方法:

class ViewController: UIViewController { 

    @IBOutlet weak var mainTextField: UITextView! 
    ... 

    func zoomIn() { 
     mainTextField.font = UIFont(name: "Helvetica Neue", size: CGFloat(18.00)) 
    } 
} 

不幸的是(和顯然對於許多你)我得到一個致命的錯誤: 「意外地發現零,同時解開可選值」。

回答

2

您正試圖從您的ViewController的新實例中調用該方法。相反,您需要在Popover VC中聲明delegate屬性,並將prepareForSegue:sender:方法中的原始父VC作爲Popover VC的委託來傳遞。

0

通過以下問題的回答Aleksandr MedvedevTheAppMentor針對另一個問題,我通過使用委託設計模式來實現此目的。如果對某人有用,我會在代碼下面發帖。

注意:我通常會看到您使用UIPopoverPresentationControllerDelegate協議,但我創建了一個自定義的(ZoomProtocol),因此可以包含我的方法(zoomOut())。

在主視圖中的控制器:

import UIKit 

// declare a protocol, that lists variables and methods 
// the delegate is expected to respond to 
protocol ZoomProtocol { 
    func zoomOut() 
} 

// set this view controller as the delegate 
class ViewController: UIViewController, ZoomProtocol { 

    ... 

    // make your presenting view controller conform to the protocol 
    zoomOut() { 
     // do something 
    } 

    // pass the this view controller as a delegate for the Popover view controller 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {   
     if let pop = segue.destination as? PopViewController { 
      pop.delegate = self 
     } 
    } 

} 

在酥料餅視圖控制器:

import UIKit 

class PopViewController: UIViewController { 

    var delegate : ZoomProtocol? 

    ... 

    // when you want to, call the method on the presenting view controller 
    @IBAction func zoomOutButtonPressed(_ sender: Any) { 
     delegate?.zoomOut() 
    } 

} 
0

在父視圖控制器,覆蓋準備建立酥料餅:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "yourPopoverIdentifier" { 
     let popoverVC = segue.destination 
     popoverVC.modalPresentationStyle = UIModalPresentationStyle.popover 
     popoverVC.popoverPresentationController!.delegate = self 
    } 
} 

然後在子視圖控制器中,您可以簡單地調用presentsViewController來訪問父級的函數。在這種情況下,父級是默認的View Controller,ViewController。

@IBAction func buttonClick(_ sender: Any) { 
    let parentVC = self.presentingViewController as! ViewController 
    parentVC.functionOnParent() 
} 
相關問題