2015-09-26 64 views
3

另一個類我有一個IBOutlet在ViewController.swift稱爲backgroundView使用IBOutlet中從迅速

class ViewController: UIViewController, SideBarDelegate { 

    @IBOutlet weak var backgroundView: UIView! 

而且我想使用IBOutlet中上SideBar.swift

@objc protocol SideBarDelegate{ 
    func sideBarDidSelectButtonAtIndex(index:Int) 
    optional func sideBarWillClose() 
    optional func sideBarWillOpen() 
} 

//When an item of the sidebar is selected, and also when the sidebar will open or close 
class SideBar: NSObject, SideBarTableViewControllerDelegate { 
    func handleSwipe(recognizer:UISwipeGestureRecognizer){ 
     let bgv = ViewController() 
     if recognizer.direction == UISwipeGestureRecognizerDirection.Right { 
      showSideBar(false) 
      delegate?.sideBarWillClose?() 
      let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light) 
      let blurView = UIVisualEffectView(effect: blurEffect) 
      blurView.frame = bgv.backgroundView.bounds 
      bgv.backgroundView.addSubview(blurView) 

     } else { 
      showSideBar(true) 
      delegate?.sideBarWillOpen?() 
     } 
    } 

但表示側時酒吧,背景不模糊。 有什麼不對?

+0

我想怎麼回事是,你必須確保ViewController是視圖控制器iboutlet連接到同一個實例。現在你只是實例化一個沒有筆尖或故事板的新的ViewController –

+0

謝謝!我明白了什麼是錯的:D – Songshil

回答

0

您實際上並未訪問該視圖控制器的實例。您創建一個新的並將其分配給bgv,然後您修改那個。

您可以通過委託來訪問它,但不能通過創建新的視圖控制器來訪問它。您還必須將其作爲變量添加到協議中。

更好的想法是將View Controller應該處理的內容移動到該類,而不是嘗試訪問該控制器的視圖。這完全違背了授權的目的。

let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light) 
let blurView = UIVisualEffectView(effect: blurEffect) 
blurView.frame = backgroundView.bounds 
backgroundView.addSubview(blurView) 

所有的代碼應該在sideBarWillClose在您的代理(視圖控制器的實現,方法)

我也建議不進行這些功能的可選的,因爲你會想父控制器能夠在菜單打開和關閉時執行操作。另外,清理你的代碼一點,更少?的

+1

我知道了 我在類ViewController中做了func sideBarWillClose(),它的工作原理是 非常感謝:) – Songshil

2
class ViewController: UIViewController, SideBarDelegate { 

    @IBOutlet weak var backgroundView: UIView! 

    var sideBar:SideBar = SideBar() 

    override func viewDidLoad() { //show side bar or not 

     sideBar = SideBar(sourceView: self.view, menuItems: ["first item", "second item", "funny item"]) 
     sideBar.delegate = self 
    } 

    func sideBarDidSelectButtonAtIndex(index: Int) { //which menuitem you take 
     if index == 2 { 
      // imageView.backgroundColor = UIColor.redColor() 
      //imageView.image    = nil 
     } else if index == 0 { 
      //imageView.image = UIImage(named: "stars") 
     } 
    } 

    func sideBarWillOpen() { 
     let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light) 
     let blurView = UIVisualEffectView(effect: blurEffect) 
     blurView.frame = backgroundView.bounds 
     backgroundView.addSubview(blurView) 
    } 
}