如何在同一个 ViewController 中初始化 NSObject 的两个实例 - Swift [英] How Do I Initialize Two Instances of NSObject in the same ViewController - Swift

查看:24
本文介绍了如何在同一个 ViewController 中初始化 NSObject 的两个实例 - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请多多包涵.我是编程新手,也是 StackOverflow 的新手.我希望我的问题能给我一个进入编程社区的温暖回应.我相信一位熟人的意见,他让我在 StackOverflow 上给他发这封电子邮件.

Please bear with me. I'm new to programming and new to StackOverflow. I hope that my question will grant me a warm response for entering the programming community. An acquaintance, whose opinion I trust, told me to post this email to him on StackOverflow.

我需要做什么才能让 NSObject 的两个实例在同一个 ViewController 中工作?我已经初始化了一个名为 SideBar 和 RightSideBar 的 NSObject 子类.它们都来自 NSObject.菜单中的单元格由我以编程方式创建的 TableViewController 创建.我遵循了一个以编程方式完成所有事情的教程,因为我不知道 Storyboard 更适合构建东西.

What do I have to do to get two instances of NSObject to work in the same ViewController? I've initialized an NSObject subclass called SideBar and RightSideBar. They both draw from NSObject. The cells in the menu are called created by a TableViewController I created programatically. I followed a tutorial that did everything programmatically because I didn't know that Storyboard is better for building things.

下面是代码库.

已抱歉啰嗦.我不知道如何使它更短更完整

EDITED: Sorry for being long winded. I don't know how to make this any shorter and as complete

============

===========

****注意 SideBar 子类是左侧菜单.RightSideBar 类具有相同的初始化程序设置并且是右侧菜单.如果可能,我希望能够让它们都出现在同一个 ViewController 的同一个实例中的同一个 ViewController 上.****

****Note the SideBar subclass is the left menu. The RightSideBar class has the same initializer setup and is the right menu. I want to be able to make them both appear on the same ViewController in the same instance of the same ViewController if possible.****

这是左边的 TableViewController:

This is the left TableViewController:

import UIKit
//this protocol of the sidebar delegate manages the selection of the item in the row.
protocol SidebarTableViewControllerDelegate {

     func sidebarControlDidSelectRow(indexPath: NSIndexPath)

}

class SidebarTableViewController: UITableViewController {

    //setting up the delegate and array of menu items.
    var delegate:SidebarTableViewControllerDelegate?
    var tableData:Array <String> = []
    var imageData:[UIImage] = []


    // MARK: - Table view data source

    //Setting up the number of sections in the menu
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return 1
    }
    //Setting up the number of items in the menu
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return tableData.count
    }

    //Setting up the menu look for the main screen after login.
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell

        if cell == nil {

            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
            //configure the cell...

            cell!.backgroundColor = UIColor.clearColor()
            cell!.textLabel?.textColor = UIColor.darkTextColor()

            let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
            selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)

            cell!.selectedBackgroundView = selectedView

        }

            cell!.textLabel!.text = tableData[indexPath.row]
            cell!.imageView!.image = imageData[indexPath.row]


            return cell!

    }

    //Setting up the height for each cell of the table
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        return 45.0

    }

    //Setting up the selection of the item in the cell.
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        delegate?.sidebarControlDidSelectRow(indexPath)
    }

    override func viewDidLoad() {

    }

    override func didReceiveMemoryWarning() {

    }

}

这是正确的表视图控制器:

This is the right table view controller:

//setting up the RightSidebarControllerDelegate
protocol RightSidebarTableViewControllerDelegate {

    func rightSidebarControlDidSelectRow(indexPath: NSIndexPath)

}

class RightSidebarTableViewController: UITableViewController {

    //setting up the delegate and array of menu items.
    var delegate:RightSidebarTableViewControllerDelegate?
    var rightTableData:Array <String> = []
    var rightImageData:[UIImage] = []


    // MARK: - Table view data source

    //Setting up the number of sections in the menu
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return 1
    }
    //Setting up the number of items in the menu
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return rightTableData.count
    }

    //Setting up the menu look for the main screen after login.
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell

        if cell == nil {

            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
            //configure the cell...

            cell!.backgroundColor = UIColor.clearColor()
            cell!.textLabel?.textColor = UIColor.darkTextColor()

            let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
            selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)

            cell!.selectedBackgroundView = selectedView

        }

        cell!.textLabel!.text = rightTableData[indexPath.row]
        cell!.imageView!.image = rightImageData[indexPath.row]


        return cell!

    }

    //Setting up the height for each cell of the table
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        return 45.0

    }

    //Setting up the selection of the item in the cell.
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        delegate?.rightSidebarControlDidSelectRow(indexPath)
    }

    override func viewDidLoad() {

    }

    override func didReceiveMemoryWarning() {

    }

}

这里是我的问题可能从 SideBar:NSObject 开始的地方.这是要初始化的左侧边栏:

Here is where my problems may start with SideBar:NSObject. This is the left SideBar to be initialized:

import UIKit

@objc protocol SideBarDelegate {

    func sideBarDidSelectButtonAtIndex (index: Int)
    optional func sideBarWillClose()
    optional func sideBarWillOpen()
    optional func sideBarWillDeinitialize()

}

//this class sets up the actual sidebar.
class SideBar: NSObject, SidebarTableViewControllerDelegate {

    //width of the bar, tableview setup, and views for the sidebar
    let barWidth:CGFloat = 175.0
    let sideBarTableViewTopInset:CGFloat = 25.0
    let sideBarContainerView:UIView = UIView()
    let sideBarTableViewController:SidebarTableViewController = SidebarTableViewController()
    var originView:UIView!

    //var for dynamic effect and controlling the sidebar
    var animator:UIDynamicAnimator!
    var delegate:SideBarDelegate?
    var isSideBarOpen:Bool = false


    //initializer for the "SideBar" class.
    override init() {
        super.init()

    }

    //initializer for the tableView of menu items.
    init(sourceView: UIView, menuItems: Array<String>, menuImages: [UIImage]){
        super.init()

        //initializing the views and animation for the menu.
        originView = sourceView
        sideBarTableViewController.tableData = menuItems
        sideBarTableViewController.imageData = menuImages
        setupSideBar()
        animator = UIDynamicAnimator(referenceView: originView)

    }

    //function for setting up the sidebar.
    func setupSideBar () {

        //setting up the frame/outline of the side bar.
        sideBarContainerView.frame = CGRectMake(-barWidth, originView.frame.origin.y + 45, barWidth, originView.frame.size.height)

        //setting up the color of the sidebar.
        sideBarContainerView.backgroundColor = UIColor.clearColor()

        //disables subviews from being confined to the sidebar.
        sideBarContainerView.clipsToBounds = false

        //placing the sidebar in the UIView
        originView.addSubview(sideBarContainerView)

        //adding blur to the menu.
        let blurView:UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
        blurView.frame = sideBarContainerView.bounds
        sideBarContainerView.addSubview(blurView)


        //setting up controls for the sidebar
        sideBarTableViewController.delegate = self
        sideBarTableViewController.tableView.frame = sideBarContainerView.bounds
        sideBarTableViewController.tableView.clipsToBounds = false

        //disabling the scroll feature. Delete to keep the scroll feature.
        sideBarTableViewController.tableView.scrollsToTop = false

        //This will remove separators in the UITableCell. Delete to keep separators.
        sideBarTableViewController.tableView.separatorStyle = UITableViewCellSeparatorStyle.None

        //This sets the background color of the sidebar and creates the inset.
        sideBarTableViewController.tableView.backgroundColor = UIColor.clearColor()
        sideBarTableViewController.tableView.contentInset = UIEdgeInsets(top: sideBarTableViewTopInset, left: 0, bottom: 0, right: 0)

        //reloads the sidebar and adds the container view to the sideBarTableViewController.
        sideBarTableViewController.tableView.reloadData()
        sideBarContainerView.addSubview(sideBarTableViewController.tableView)
    }

    func showSideBar(shouldOpen: Bool){
        animator.removeAllBehaviors()
        isSideBarOpen = shouldOpen

        //simple if and else statements to define the direction of animation and intensity of animation
        let gravityX:CGFloat = (shouldOpen) ? 0.5 : -0.5
        let magnitude:CGFloat = (shouldOpen) ? 20 : -20
        let boundaryX:CGFloat = (shouldOpen) ? barWidth : -barWidth

        //controls the behavior of the animation.
        let gravityBehavior: UIGravityBehavior = UIGravityBehavior(items: [sideBarContainerView])
        gravityBehavior.gravityDirection = CGVectorMake(gravityX, 0)
        animator.addBehavior(gravityBehavior)

        let collisionBehavior: UICollisionBehavior = UICollisionBehavior(items: [sideBarContainerView])
        collisionBehavior.addBoundaryWithIdentifier("sideBarBoundary", fromPoint: CGPointMake(boundaryX, 20), toPoint: CGPointMake(boundaryX, originView.frame.size.height))
        animator.addBehavior(collisionBehavior)

        let pushBehavior:UIPushBehavior = UIPushBehavior(items: [sideBarContainerView], mode: UIPushBehaviorMode.Instantaneous)
        pushBehavior.magnitude = magnitude
        animator.addBehavior(pushBehavior)

        let sideBarBehavior:UIDynamicItemBehavior = UIDynamicItemBehavior(items: [sideBarContainerView])
        sideBarBehavior.elasticity = 0.3
        animator.addBehavior(sideBarBehavior)
    }
    func sidebarControlDidSelectRow(indexPath: NSIndexPath) {
        delegate?.sideBarDidSelectButtonAtIndex(indexPath.row)
    }

}

这是右侧的 SideBar:NSObject,最终将初始化右侧菜单.

This is the right SideBar:NSObject that will eventually initialize the right menu.

import UIKit
@objc protocol RightSideBarDelegate {

    func rightSideBarDidSelectButtonAtIndex (index: Int)
    optional func sideBarWillClose()
    optional func sideBarWillOpen()

}

class RightSideBar: NSObject, RightSidebarTableViewControllerDelegate {

    //width of the bar, tableview setup, and views for the sidebar
    let barWidth:CGFloat = 175.0
    let rightSideBarTableViewTopInset:CGFloat = 25.0
    let rightSideBarContainerView:UIView = UIView()
    let rightSideBarTableViewController:RightSidebarTableViewController = RightSidebarTableViewController()
    var rightOriginView:UIView!

    //var for dynamic effect and controlling the sidebar
    var animator:UIDynamicAnimator!
    var delegate:RightSideBarDelegate?
    var isSideBarOpen:Bool = false


    //initializer for the "SideBar" class.
    override init() {
        super.init()

    }

    //initializer for the tableView of menu items.
    init(rightSourceView: UIView, rightMenuItems: Array<String>, rightMenuImages: [UIImage]){
        super.init()

        //initializing the views and animation for the menu.
        rightOriginView = rightSourceView
        rightSideBarTableViewController.rightTableData = rightMenuItems
        rightSideBarTableViewController.rightImageData = rightMenuImages
        setupSideBar()
        animator = UIDynamicAnimator(referenceView: rightOriginView)

    }

    //function for setting up the sidebar.
    func setupSideBar () {

        //setting up the frame/outline of the side bar.
        rightSideBarContainerView.frame = CGRectMake(rightOriginView.frame.size.width + barWidth , rightOriginView.frame.origin.y + 45, barWidth, rightOriginView.frame.size.height)

        //setting up the color of the sidebar.
        rightSideBarContainerView.backgroundColor = UIColor.clearColor()

        //disables subviews from being confined to the sidebar.
        rightSideBarContainerView.clipsToBounds = false

        //placing the sidebar in the UIView
        rightOriginView.addSubview(rightSideBarContainerView)

        //adding blur to the menu.
        let blurView:UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
        blurView.frame = rightSideBarContainerView.bounds
        rightSideBarContainerView.addSubview(blurView)


        //setting up controls for the sidebar
        rightSideBarTableViewController.delegate = self
        rightSideBarTableViewController.tableView.frame = rightSideBarContainerView.bounds
        rightSideBarTableViewController.tableView.clipsToBounds = false

        //disabling the scroll feature. Delete to keep the scroll feature.
        rightSideBarTableViewController.tableView.scrollsToTop = false

        //This will remove separators in the UITableCell. Delete to keep separators.
        rightSideBarTableViewController.tableView.separatorStyle = UITableViewCellSeparatorStyle.None

        //This sets the background color of the sidebar and creates the inset.
        rightSideBarTableViewController.tableView.backgroundColor = UIColor.clearColor()
        rightSideBarTableViewController.tableView.contentInset = UIEdgeInsets(top: rightSideBarTableViewTopInset, left: 0, bottom: 0, right: 0)

        //reloads the sidebar and adds the container view to the rightSideBarTableViewController.
        rightSideBarTableViewController.tableView.reloadData()
        rightSideBarContainerView.addSubview(rightSideBarTableViewController.tableView)

    }

    func showSideBar(shouldOpen: Bool){
        animator.removeAllBehaviors()
        isSideBarOpen = shouldOpen

        //simple if and else statements to define the direction of animation and intensity of animation
        let gravityX:CGFloat = (shouldOpen) ? -0.5 : 0.5
        let magnitude:CGFloat = (shouldOpen) ? -20 : 20
        let boundaryX:CGFloat = (shouldOpen) ? -barWidth : barWidth

        //controls the behavior of the animation.
        let gravityBehavior: UIGravityBehavior = UIGravityBehavior(items: [rightSideBarContainerView])
        gravityBehavior.gravityDirection = CGVectorMake(gravityX, 0)
        animator.addBehavior(gravityBehavior)

        let collisionBehavior: UICollisionBehavior = UICollisionBehavior(items: [rightSideBarContainerView])
        collisionBehavior.addBoundaryWithIdentifier("sideBarBoundary", fromPoint: CGPointMake(boundaryX, 20), toPoint: CGPointMake(boundaryX, rightOriginView.frame.size.height))
        animator.addBehavior(collisionBehavior)

        let pushBehavior:UIPushBehavior = UIPushBehavior(items: [rightSideBarContainerView], mode: UIPushBehaviorMode.Instantaneous)
        pushBehavior.magnitude = magnitude
        animator.addBehavior(pushBehavior)

        let sideBarBehavior:UIDynamicItemBehavior = UIDynamicItemBehavior(items: [rightSideBarContainerView])
        sideBarBehavior.elasticity = 0.3
        animator.addBehavior(sideBarBehavior)


    }
    func rightSidebarControlDidSelectRow(indexPath: NSIndexPath) {
        delegate?.rightSideBarDidSelectButtonAtIndex(indexPath.row)
    }

}

最后,这是我当前的 DoubleMenuViewController 代码.当我继续使用 DoubleMenuViewController 来打破菜单时会发生一些事情.菜单甚至不会加载.但是,如果我在一个只调用 SideBar:NSObject 的 SingleMenuViewController 中,那么只要我只调用一个菜单,代码就可以工作.在这个 DoubleMenuViewController 中,我将 RightSideBar 类的初始化部分注释掉了,因为我正在研究解决方案.我知道这个 ViewController 的这段代码是乱码.我正在尝试我能想到的一切.在代码后查看我的评论以了解我尝试过的内容:

Finally this is my current code for the DoubleMenuViewController. Something happens when I segue to the DoubleMenuViewController to break the menus. The menus won't even load. However, if I'm in a SingleMenuViewController that only calls SideBar:NSObject then the code will work so long as I'm only calling one menu. In this DoubleMenuViewController, I have the initialization section commented out for the RightSideBar class because I'm working on a solution. I know this code for this ViewController is garbled. I'm trying everything I can think of. See my remarks after the code to see what I've tried:

import UIKit

class DoubleMenuViewController: UIViewController, SideBarDelegate,       RightSideBarDelegate {

    var sideBar:SideBar?
    var ondemandSideBar:SideBar {

        get {

            if sideBar == nil {

            //setting up the menu items for the sidebar.
            sideBar = SideBar(sourceView: self.view, menuItems: ["Home", "Share", "About", "Help"], menuImages: [homeImage!, shareImage!, aboutImage!, helpImage!])
            sideBar!.delegate = self
            SideBar.new()

            }

            return sideBar!
        }
    }

    //initializes the "RightSideBar"
    var rightSideBar:RightSideBar?
    var ondemandRightSideBar:RightSideBar {

        get {

            if rightSideBar == nil {

            rightSideBar = RightSideBar(rightSourceView: self.view, rightMenuItems: [//Other items], rightMenuImages: [//Other Items])
            rightSideBar!.delegate = self
            RightSideBar.new()

            }

            return rightSideBar!
        }
    }


    var homeImage = UIImage(named: "Home")
    var shareImage = UIImage(named: "Share")
    var aboutImage = UIImage(named: "About")
    var helpImage = UIImage(named: "Help")

    @IBOutlet weak var currentMenuControl: UIBarButtonItem!

    @IBAction func currentMenuDisplay(sender: AnyObject) {

        if currentMenuControl.tag == 1 {

            ondemandSideBar.showSideBar(true)
            currentMenuControl.tag = 0

        } else {

            ondemandSideBar.showSideBar(false)
            currentMenuControl.tag = 1

        }

    }

    @IBOutlet weak var progressionMenuControl: UIBarButtonItem!

    @IBAction func progressionMenuDisplay(sender: AnyObject) {

        if progressionMenuControl.tag == 1 {

            ondemandRightSideBar.showSideBar(true)
            progressionMenuControl.tag = 0

        } else {

            ondemandRightSideBar.showSideBar(false)
            progressionMenuControl.tag = 1
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func sideBarDidSelectButtonAtIndex(index: Int) {

        switch index {

         //segues
        }
    }

    func rightSideBarDidSelectButtonAtIndex(index: Int) {

        switch index {

         //segues
        }
    }

}

这是我尝试过的:

  1. 我尝试改变 CGFloats 的位置,因为 SubViews 似乎从左边来.

  1. I've tried altering the positioning of CGFloats since SubViews seem to come from the left.

我重命名了所有 RightSideBar 变量和类名一切克服实例变量中的运行时混淆和类名.这包括重命名您在NSObject 子类和目标视图控制器.

I've renamed all the RightSideBar variables and class names everything to overcome a runtime confusion in instance variables and class names. This includes renaming the initializers that you saw in the NSObject SubClass and the target view controller.

我尝试在 viewDidLoad 方法中使用控制流按钮标签.我取消了滑动功能以显示菜单和添加按钮是因为我认为系统难以处理滑动.

I've tried using control flow in the viewDidLoad method with a button tag. I took away the swipe features to show the menu and added buttons because I thought system was struggling to deal with the Swipes.

我尝试在 NSObject 的 SideBar 子类文件中取消初始化.让我陷入困境的只是一个导致应用程序崩溃的无限循环登录后.

I've tried deinitializing in the SideBar subclass file of NSObject. All that got me was an infinite loop that crashed the application after login.

然后我尝试在targetViewController.....DoubleMenuViewController 和单菜单视图控制器.我回到了带有按钮的工作菜单在 SingleMenuViewController 中,但它仍然不会显示左侧和DoubleMenuViewController 中的右侧菜单.

Then I tried ondemand initialization in the targetViewController.....DoubleMenuViewController and SingleMenuViewController. I returned to a working menu with buttons in the SingleMenuViewController but it still won't show the left and right menu in the DoubleMenuViewController.

最后我尝试取消初始化 DoubleMenuViewController 中的 SideBar(左侧 SideBar)和 RightSideBar.但是,当我将 println() 函数添加到我的所有部分时,调试器不会为我运行打印函数来获取对象的值,甚至不会显示像 "This" 这样的类型状态.我添加了打印功能,因为我不确定我是否会知道何时发生取消初始化和重新初始化.

Last I tried deinitializing the SideBar (left SideBar) and the RightSideBar in the DoubleMenuViewController. However, when I add println() functions to all my sections the debugger doesn't run the print function for me to get values of objects or even show typed states like "This". I added the print functions because I wasn't sure if I would know when deinitialization and reinitialization occurred.

我的菜单似乎是从 SideBar:NSObject 文件和 RightSideBar:NSObject 文件初始化的.我的意思是我的菜单是在我点击目标视图控制器之前创建的.只要我能让编译器在同一个视图控制器中初始化 SideBar 和 RightSideBar,这对我来说就不是问题,但它不会这样做.

It seems that my menu is initialized from the SideBar: NSObject file and the RightSideBar:NSObject file. What I mean is that my menu is being created before I hit the target view controller. This isn't a problem for me so long as I can get the compiler to initialize the SideBar and the RightSideBar in the same View Controller, but it won't do that.

我只需要能够通过滑动或点击按钮来控制两个菜单.

I just need to be able to control both menus with swipes or button taps.

我认为我的初始值设定项相互覆盖有问题.

I think I have a problem with my initializers overriding each other.

但是,我不知道如何解决这个问题.我已经通读了 Swift 手册并阅读了互联网上的文章.我也搜索过 StackOverflow.

However, I don't know how to fix that problem. I've read through the Swift manual and read articles on the internet. I've also searched StackOverflow.

推荐答案

你问:

如何在同一个视图控制器中初始化 NSObject 的两个实例?

How do I Initialize two instances of NSObject in the same view controller?

暂且不谈为什么要处理 NSObject(在 Objective-C 中,所有类最终都必须从 NSObject 继承,而在 Swift 中则不再如此),如果你想实例化两个对象,你只需要为每个对象拥有一个属性.

Setting aside why you're dealing with NSObject at all (in Objective-C all classes have to subclass from NSObject ultimately, in Swift that's no longer the case), if you want to instantiate two objects, you simply have to have one property for each.

如果这些是延迟实例化的,如您的代码片段所建议的,那么您必须确定引用该延迟实例化的属性的位置(例如,您可能会从从边缘滑动"手势中触发它)或您有什么.在引用延迟实例化属性的代码中设置一个断点,并确保您完全到达那里.

If these are lazily instantiated, as your code snippet suggests, then you have to identify where that lazily instantiated property is referenced (e.g. you might trigger it from a "swipe from edge" gesture) or what have you. Set a breakpoint in the code that references that lazily instantiated property and make sure you're getting there at all.

--

我对您的代码片段之一进行了一些观察.你说你正在像这样实例化你的侧边栏:

I had some observations on one of your code snippets. You say that you're instantiating your side bar like so:

var sideBar : SideBar?
var ondemandSideBar : SideBar {
    get {
        if sideBar == nil {
            sideBar = SideBar(sourceView, menuItems, menuImage etc.)
            sideBar!.delegate
            SideBar.new()
        }
    }
}

我认为这不是您真正在做的事情,因为您没有设置委托,而是在实例化 SideBar 以及调用 new(您不应该在 Swift 中这样做),您没有返回值等.

I don't think that's what you're really doing because you're not setting the delegate, you're both instantiating the SideBar as well as calling new (which you shouldn't be doing from Swift), you're not returning a value, etc.

此外,具有由某些计算属性实例化的存储属性的模式具有特定的 Objective-C je ne sais quoi. 我推断您想要一个延迟实例化的属性.如果是这种情况,我会倾向于使用单个 lazy 存储属性.然后我会使用闭包懒惰地设置该属性:

Also, that pattern of having a stored property that is instantiated by some computed property has a certain Objective-C je ne sais quoi. I'm inferring that you want a lazily instantiated property. If that's the case, I'd be inclined to use a single lazy stored property. And I'd then set that property lazily using a closure:

我期待这种模式

protocol SideBarDelegate : class {                         // specify class so we can use `weak` reference
    func didChooseMenuItem(sender: SideBar, item: Int)
}

class SideBar {
    weak var delegate: SideBarDelegate?                    // make sure this is weak to avoid strong reference cycle
}

class ViewController: UIViewController, SideBarDelegate {

    lazy var sideBar: SideBar = {
        let _sideBar = SideBar(sourceView, menuItems, menuImage, etc.)
        _sideBar.delegate = self
        return _sideBar
    }()

    func didChooseMenuItem(sender: SideBar, item: Int) {
        // handle it here
    }

    // etc.
}

这样,在您在代码中的某处引用 sideBar 之前,sideBar 不会被实例化,但是当您这样做时,它将使用其中的代码实例化关闭.

This way, the sideBar won't be instantiated until you reference sideBar somewhere in your code, but when you do, it will be instantiated with the code inside that closure.

这篇关于如何在同一个 ViewController 中初始化 NSObject 的两个实例 - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆