在swift中使用来自另一个类的IBOutlet

时间:2015-09-26 02:57:53

标签: swift iboutlet

我在ViewController.swift中有一个名为backgroundView

的IBOutlet
class ViewController: UIViewController, SideBarDelegate {

    @IBOutlet weak var backgroundView: UIView!

我想在SideBar.swift上使用那个IBOutlet

@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?()
        }
    }

但是在显示侧栏时,背景并不模糊。 有什么问题?

2 个答案:

答案 0 :(得分: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)
    }
}

答案 1 :(得分:0)

您实际上并没有访问该视图控制器的实例。您创建一个新的并将其分配给bgv,然后您修改它。

您可以通过委托访问它,但不能通过创建新的视图控制器来访问它。您还必须将其作为变量添加到协议中。

更好的想法是将View Controller应该处理的内容移动到该类,而不是尝试访问该控制器的视图。这完全违背了授权的目的。

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

所有代码都应该放在代理中的sideBarWillClose中(视图控制器对该方法的实现)

我还建议不要让这些功能可选,因为您希望父控制器能够在菜单打开和关闭时执行操作。另外,这样可以清理你的代码,更少?'