IOS SWIFT : 当我的 Popover 单元格之一被选中时更改我的 BarButtonItem 标题

IOS SWIFT : Change My BarButtonItem Title when one of my Popover cell is selected

抱歉 IOS Swift 中的新手。只是想问一下,当我的 Popover 单元格之一被选中时,如何更改我的 BatButtonItem 标题。即使我使用委托方法。但是我还是不行。

示例: Here is My Storyboard

我的在这里运行不正常。

这是我的 HOMEVC.swift(完整代码)

//
//  HomeVC.swift
//  SwiftLoginScreen
//
//  Created by Dipin Krishna on 31/07/14.
//  Copyright (c) 2014 Dipin Krishna. All rights reserved.

import UIKit
import AFNetworking
import FontAwesome_swift
import KeychainAccess

class HomeVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UIPopoverPresentationControllerDelegate, LanguageViewControllerDelegate {

    @IBOutlet weak var dashboardOpen: UIBarButtonItem!
    @IBOutlet var usernameLabel : UILabel!
    @IBOutlet weak var Open: UIBarButtonItem!
    @IBOutlet weak var dashboard_icon1: UILabel!
    @IBOutlet weak var card_view1: UIView!
    @IBOutlet weak var sub_card_view1: UIView!
    @IBOutlet weak var dashboard_icon2: UILabel!
    @IBOutlet weak var card_view2: UIView!
    @IBOutlet weak var sub_card_view2: UIView!
    @IBOutlet weak var dashboard_icon3: UILabel!
    @IBOutlet weak var card_view3: UIView!
    @IBOutlet weak var sub_card_view3: UIView!
    @IBOutlet weak var dashboard_icon4: UILabel!
    @IBOutlet weak var theScrollView: UIScrollView!
    @IBOutlet weak var card_view4: UIView!
    @IBOutlet weak var sub_dashboard_icon: UILabel!
    @IBOutlet weak var sub_dashboard_icon2: UILabel!
    @IBOutlet weak var sub_dashboard_icon3: UILabel!
    @IBOutlet weak var currentTimeLabel: UILabel!
    @IBOutlet weak var currentTimeLabel2: UILabel!
    @IBOutlet weak var currentTimeLabel3: UILabel!
    @IBOutlet weak var card_view5: UITableView!
    @IBOutlet weak var calendarView: NWCalendarView!
    //@IBOutlet weak var ticketBtn: UIBarButtonItem!
    @IBOutlet weak var barButtonItem: UIBarButtonItem!
    @IBOutlet weak var companyWalletBalance: UILabel!
    @IBOutlet weak var cashWalletBalance: UILabel!
    @IBOutlet weak var signupWalletBalance: UILabel!
    @IBOutlet weak var viewStatement1: UILabel!
    @IBOutlet weak var viewStatement2: UILabel!
    @IBOutlet weak var viewStatement3: UILabel!
    @IBOutlet weak var languageTextField: UITextField!

    public static var menuAPI = Json4Swift_Base.init()
    public static var ticketAPI = TicketAPIResponse.init()
    var timer = NSTimer()
    var sections : [Section] = SectionsData().getSectionsFromData()
    public static var tableData: [String] = []
    public static var tableDate: [String] = []
    let navigationBar = UINavigationBar(frame: CGRectMake(108, 0, 110, 64))
    let navItem = UINavigationItem.init(title: "My Home")

    //var pickOption = ["English", "简体", "繁体"]
    //var segmentedControl: HMSegmentedControl = HMSegmentedControl(sectionTitles: ["One", "Two"])


    override func viewDidLoad() {
        super.viewDidLoad()


        // For UIBar Button Item Title (English) //
        let font = UIFont.boldSystemFontOfSize(14)
        barButtonItem.setTitleTextAttributes([NSFontAttributeName: font], forState:UIControlState.Normal)

        doLocalize()
        //SwiftSpinner.showWithDelay(0.1, title: "Loading...")
        //SwiftSpinner.hide()

        // For UINavigation Bar //
        navigationBar.barTintColor = UIColor(red: 1.0/255.0, green: 164.0/255.0, blue: 161.0/255.0, alpha: 0.5)
        navigationBar.clipsToBounds = true
        navigationBar.items = [navItem]
        let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
        navigationBar.titleTextAttributes = titleDict as! [String : AnyObject]
        self.view.addSubview(navigationBar)

        calendarView.layer.borderWidth = 1
        calendarView.layer.borderColor = UIColor.lightGrayColor().CGColor
        calendarView.backgroundColor = UIColor.whiteColor()

        // For Calendar //
        let date = NSDate()
        print(date)
        let newDate3 = date.dateByAddingTimeInterval(60*60)
        calendarView.selectedDates = [newDate3]
        calendarView.selectionRangeLength = 1
        calendarView.createCalendar()
        calendarView.scrollToDate(newDate3, animated: true)

        // For Scrolling //
        let subview = theScrollView.subviews[0] as! UIView;
        //Make the scroll view's contentSize the same size as the content view.
        theScrollView!.contentSize = subview.bounds.size;

        // For Side Menu (With Swap) //
        dashboardOpen.target = self.revealViewController()
        dashboardOpen.action = Selector("revealToggle:")
        self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

        // For Dashboard Icon //
        dashboard_icon1.font = UIFont.fontAwesomeOfSize(40)
        dashboard_icon1.text = String.fontAwesomeIconWithCode("fa-money")
        dashboard_icon2.font = UIFont.fontAwesomeOfSize(40)
        dashboard_icon2.text = String.fontAwesomeIconWithCode("fa-money")
        dashboard_icon3.font = UIFont.fontAwesomeOfSize(40)
        dashboard_icon3.text = String.fontAwesomeIconWithCode("fa-money")
        dashboard_icon4.font = UIFont.fontAwesomeOfSize(40)
        dashboard_icon4.text = String.fontAwesomeIconWithCode("fa-clock-o")
        sub_dashboard_icon.font = UIFont.fontAwesomeOfSize(20)
        sub_dashboard_icon.text = String.fontAwesomeIconWithCode("fa-arrow-circle-o-right")
        sub_dashboard_icon2.font = UIFont.fontAwesomeOfSize(20)
        sub_dashboard_icon2.text = String.fontAwesomeIconWithCode("fa-arrow-circle-o-right")
        sub_dashboard_icon3.font = UIFont.fontAwesomeOfSize(20)
        sub_dashboard_icon3.text = String.fontAwesomeIconWithCode("fa-arrow-circle-o-right")

        // For Dashboard Radius //
        card_view1.layer.masksToBounds = true;
        card_view1.layer.cornerRadius = 5.0;

        let path1 = UIBezierPath(roundedRect:sub_card_view1.bounds, byRoundingCorners:[.BottomRight, .BottomLeft], cornerRadii: CGSizeMake(5, 5))
        let maskLayer1 = CAShapeLayer()
        maskLayer1.path = path1.CGPath
        sub_card_view1.layer.mask = maskLayer1

        card_view2.layer.masksToBounds = true;
        card_view2.layer.cornerRadius = 5.0;

        let path2 = UIBezierPath(roundedRect:sub_card_view2.bounds, byRoundingCorners:[.BottomRight, .BottomLeft], cornerRadii: CGSizeMake(5, 5))
        let maskLayer2 = CAShapeLayer()
        maskLayer2.path = path2.CGPath
        sub_card_view2.layer.mask = maskLayer2

        card_view3.layer.masksToBounds = true;
        card_view3.layer.cornerRadius = 5.0;

        let path3 = UIBezierPath(roundedRect:sub_card_view3.bounds, byRoundingCorners:[.BottomRight, .BottomLeft], cornerRadii: CGSizeMake(5, 5))
        let maskLayer3 = CAShapeLayer()
        maskLayer3.path = path3.CGPath
        sub_card_view3.layer.mask = maskLayer3

        card_view4.layer.masksToBounds = true;
        card_view4.layer.cornerRadius = 5.0;

        card_view5.layer.masksToBounds = true;
        card_view5.layer.cornerRadius = 5.0;

        calendarView.layer.masksToBounds = true;
        calendarView.layer.cornerRadius = 5.0;

        // For Dashboard Current Time //
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0,
            target: self,
            selector: Selector("tick"),
            userInfo: nil,
            repeats: true)

        // Do any additional setup after loading the view.

    }

    func changeName(text: String) {

        self.barButtonItem.title = "\(text)" // For get barButton you should create IBOutlet for barButtonItem
        print(self.barButtonItem.title)

    }

    @objc func tick() {

        let date1 = NSDate()
        let dateFormatter1 = NSDateFormatter()
        dateFormatter1.dateFormat = "dd MMMM yyyy"
        let timeZone1 = NSTimeZone(name: "GMT+8")
        dateFormatter1.timeZone = timeZone1

        let date2 = NSDate()
        let dateFormatter2 = NSDateFormatter()
        dateFormatter2.dateFormat = "EEEE"
        let timeZone2 = NSTimeZone(name: "GMT+8")
        dateFormatter2.timeZone = timeZone2


        currentTimeLabel.text = dateFormatter1.stringFromDate(date1)

        currentTimeLabel2.text = dateFormatter2.stringFromDate(date2)

        currentTimeLabel3.text = NSDateFormatter.localizedStringFromDate(NSDate(),
            dateStyle: .NoStyle,
            timeStyle: .MediumStyle)

        var day:String = ""
        day = currentTimeLabel2.text!

        if (day.containsString("Sunday")){

            currentTimeLabel2.text = Localization("Sunday")
        }
        else if (day.containsString("Monday")){

            currentTimeLabel2.text = Localization("Monday")
        }
        else if (day.containsString("Tuesday")){

            currentTimeLabel2.text = Localization("Tuesday")

        }
        else if (day.containsString("Wednesday")){

            currentTimeLabel2.text = Localization("Wednesday")
        }
        else if (day.containsString("Thursday")){

            currentTimeLabel2.text = Localization("Thursday")
        }
        else if (day.containsString("Friday")){

            currentTimeLabel2.text = Localization("Friday")
        }
        else{
            currentTimeLabel2.text = Localization("Saturday")
        }
    }


    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)


        let parameters1 = ["ActionType":"default","LanguageCode":stringLang,"Token":result]
        manager.POST(CONFIG_URL,
            parameters: parameters1,
            success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
                print("JSON: " + responseObject.description)

                var responseDict = responseObject as! Dictionary<String, AnyObject>

                let dashboardAPI = DashboardAPIResponse(dictionary: responseDict)


            },
            failure: { (operation: AFHTTPRequestOperation?,error: NSError!) -> Void in
                print("Error: " + error.localizedDescription)
        })


        let parameters = ["ActionType":"menu","LanguageCode":stringLang,"Token":result]
        manager.POST(CONFIG_URL,
            parameters: parameters,
            success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
                print("JSON: " + responseObject.description)

                var responseDict = responseObject as! Dictionary<String, AnyObject>


                HomeVC.menuAPI = Json4Swift_Base(dictionary: responseDict)
                var tempArray = HomeVC.menuAPI?.result


                for var i = 0; i < tempArray!.count ; ++i {
                    let level1 = tempArray![i].module
                    let level2 = tempArray![i].subModule

                    for var i = 0; i < level1!.count ; ++i {
                        print(level1![i].icon)
                        print(level1![i].label)

                    }

                    for var i = 0; i < level2!.count ; ++i {
                        print(level2![i].label)
                        var level3 = level2![i].function

                        for var i = 0; i < level3!.count ; ++i {
                            print(level3![i].label)
                            print(level3![i].menuLink)
                            print(level3![i].uRL)

                        }
                    }
                }

            },
            failure: { (operation: AFHTTPRequestOperation?,error: NSError!) -> Void in
                print("Error: " + error.localizedDescription)
        })
    }

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

    func doLocalize(){

        companyWalletBalance.text = Localization("companyWalletBalance")
        cashWalletBalance.text = Localization("cashWalletBalance")
        signupWalletBalance.text = Localization("signupWalletBalance")
        currentTimeLabel2.text = Localization("currentTimeLabel2")
        viewStatement1.text = Localization("viewStatement")
        viewStatement2.text = Localization("viewStatement")
        viewStatement3.text = Localization("viewStatement")
        navItem.title = Localization("navItem")
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        return sections[section].heading
    }

    func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

        // Text Color
        var header: UITableViewHeaderFooterView = (view as! UITableViewHeaderFooterView)
        header.textLabel!.textColor = UIColor.whiteColor()
        header.contentView.backgroundColor = UIColor.blackColor()
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return sections.count

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return sections[section].items.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

            var mycell = tableView.dequeueReusableCellWithIdentifier("sectionsCell", forIndexPath: indexPath) as! MyCustomTableViewCell
            mycell.label1.text = sections[indexPath.section].items[indexPath.row]
            mycell.label2.text = sections[indexPath.section].items[indexPath.row]
            mycell.label3.text = sections[indexPath.section].items[indexPath.row]
            mycell.label4.text = sections[indexPath.section].items[indexPath.row]
            return mycell
    }

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40.0
    }

    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle
    {
        return UIModalPresentationStyle.None
    }


    @IBAction func languageButton(sender: AnyObject) {

        let storyboard : UIStoryboard = UIStoryboard(name: "Storyboard", bundle: nil)
        var menuViewController: LanguageViewController = storyboard.instantiateViewControllerWithIdentifier("LanguageViewController") as! LanguageViewController
        menuViewController.delegate = self // Put this Line
        menuViewController.modalPresentationStyle = .Popover
        menuViewController.preferredContentSize = CGSizeMake(50, 100)

        let popoverMenuViewController = menuViewController.popoverPresentationController
        popoverMenuViewController?.permittedArrowDirections = .Any
        popoverMenuViewController?.delegate = self
        popoverMenuViewController?.sourceView = menuViewController.view
        popoverMenuViewController?.sourceRect = CGRect(x:240, y:35, width: 1, height: 1)
        presentViewController(menuViewController, animated: true, completion: nil)

    }

    @IBAction func dashboardLogout(sender: AnyObject) {

        let parameters = ["ActionType":"logout"]
        manager.POST(CONFIG_URL,
            parameters: parameters,
            success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
                print("JSON: " + responseObject.description)

                // CLEAN COOKIES //

                let cookie = NSHTTPCookie.self
                let cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
                for cookie in cookieJar.cookies! {
                    print(cookie.name+"="+cookie.value)
                    cookieJar.deleteCookie(cookie)
                }

                var revealViewControler :SWRevealViewController =  self.revealViewController()
                let webViewController = self.storyboard!.instantiateViewControllerWithIdentifier("SWRevealViewController") as! SWRevealViewController

                revealViewControler.pushFrontViewController(webViewController, animated: true)


            },
            failure: { (operation: AFHTTPRequestOperation?,error: NSError!) -> Void in
                print("Error: " + error.localizedDescription)
        })

    }


}

// For Date + Time //
extension NSDate {
    var formattedd:String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter.stringFromDate(self)
    }
    func formatteddWith(format:String) -> String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = format
        return formatter.stringFromDate(self)
    }
}

// For Date + Time //
extension String {
    var asDatee:NSDate! {
        let styler = NSDateFormatter()
        styler.dateFormat = "yyyy-MM-dd"
        return styler.dateFromString(self)!
    }
    func asDateFormatteddWith(format:String) -> NSDate! {
        let styler = NSDateFormatter()
        styler.dateFormat = format
        return styler.dateFromString(self)!
    }

}

HERE IS MY LANGUAGEVIEWCONTROLLER.swift(显示 Popover 内容的地方)

//
//  LanguageViewController.swift
//  SwiftLoginScreen
//
//  Created by User on 3/21/16.
//  Copyright © 2016 Dipin Krishna. All rights reserved.
//

import UIKit
import AFNetworking

protocol LanguageViewControllerDelegate{
    func changeName(text:String)
}

class LanguageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


    @IBOutlet weak var tableView: UITableView!

    var delegate:LanguageViewControllerDelegate! = nil
    var arrLanguage: [String] = ["English", "简体", "繁体"]


    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.tableFooterView = UIView()

        // Do any additional setup after loading the view, typically from a nib.
        //self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)

    }


    func tableView(tableView: UITableView, didselectRowAtIndexPath indexPath: NSIndexPath) {

        delegate!.changeName(arrLanguage[indexPath.row])
        tableView.delegate = self

    }


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrLanguage.count;
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell:LanguageTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("LanguageTableViewCell") as! LanguageTableViewCell

        cell.languageLabel.text = arrLanguage[indexPath.row]

        return cell
    }


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

    // For Popover Frame Size //
    override var preferredContentSize: CGSize {
        get
        {
            return CGSize(width: 150, height: 130)
        }
        set
        {
            super.preferredContentSize = newValue
        }
    }
}

这是我的 LANGUAGETABLEVIEWCELL.swift

//
//  LanguageTableViewCell.swift
//  SwiftLoginScreen
//
//  Created by User on 3/21/16.
//  Copyright © 2016 Dipin Krishna. All rights reserved.
//

import UIKit

class LanguageTableViewCell: UITableViewCell {

    @IBOutlet weak var languageLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

当我尝试调试这部分代码时,当我的代码 运行 时,它不会通过这段代码。为什么?

func changeName(text: String) {

        self.barButtonItem.title = "\(text)" // For get barButton you should create IBOutlet for barButtonItem
        print(self.barButtonItem.title)

    }

请帮忙。

第 1 步:在 LanguageViewController 中制定一个您将发送数据的协议。

protocol LanguageViewControllerDelegate{
    func changeName(text:String)
}

Step2:在发送中声明委托class(即HOMEVC)

class LanguageViewController: UIViewController {
    var delegate:LanguageViewControllerDelegate! = nil
   [...]
 }

Step3:在一个class方法中使用delegate将数据发送给接收方法,接收方法可以是任何采用该协议的方法

 func tableView(tableView: UITableView, didselectRowAtIndexPath indexPath: NSIndexPath) {
     delegate!.changeName(arrLanguage[indexPath.row])
 }

第四步:接收时采用协议class

 class HomeViewController: UIViewController,LanguageViewControllerDelegate { }

第 5 步:实现委托方法(HomeViewController - 如您的问题)

func changeName(text: String) {
    self.barButton.title = "\(text)" // For get barButton you should create IBOutlet for barButtonItem
}

第 6 步: 在弹出框的 BarButtonItem 的操作按钮中设置委托:

   @IBAction func languageButton(sender: AnyObject) {
        let storyboard : UIStoryboard = UIStoryboard(name: "Storyboard", bundle: nil)
        var menuViewController: LanguageViewController = storyboard.instantiateViewControllerWithIdentifier("LanguageViewController") as! LanguageViewController
        menuViewController.modalPresentationStyle = .Popover
        menuViewController.preferredContentSize = CGSizeMake(50, 100)
        menuViewController.delegate = self // Put this Line
        let popoverMenuViewController = menuViewController.popoverPresentationController
        popoverMenuViewController?.permittedArrowDirections = .Any
        popoverMenuViewController?.sourceView = menuViewController.view
        popoverMenuViewController?.delegate = self
        popoverMenuViewController?.sourceRect = CGRect(x:240, y:35, width: 1, height: 1)
        presentViewController(menuViewController, animated: true, completion: nil)
   }

Yoy 应该将 tableView 委托和数据源放在 viewDidLoad() 中:-

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self 
    tableView.tableFooterView = UIView()
}

和 tableView didSelectRow :-

 func tableView(tableView: UITableView, didselectRowAtIndexPath indexPath: NSIndexPath) {
    delegate!.changeName(arrLanguage[indexPath.row])
}

希望这会奏效....