无需代理即可快速呈现当前视图

时间:2019-03-12 19:28:28

标签: ios swift mobile segue uistoryboardsegue

我有一个表视图,该表视图包含以编程方式生成的单元格上的按钮,可为我的应用程序创建菜单,但我想使每个单元格上的按钮转到不同的视图控制器。这是生成单元的代码。

import UIKit


class MenuViewController: UIViewController, SwitchView {
    let titles: [String] = ["Previous Issues", "Bookmarks", "Settings", "Website", "About"]
    let images: [UIImage] = [#imageLiteral(resourceName: "newspaper.png"),#imageLiteral(resourceName: "bookmark-outline.png"),#imageLiteral(resourceName: "settings.png"),#imageLiteral(resourceName: "outside-page.png"),#imageLiteral(resourceName: "info.png")]
    var menuItems: [menuItem] = []
    public var index: Int = 0



override func viewDidLoad() {
    super.viewDidLoad()
    menuItems = createMenu()
}

override func viewDidAppear(_ animated: Bool) {
}

func switchView(index: Int){
    NSLog("THIS CODE IS RUNNING")
    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let newViewController = storyBoard.instantiateViewController(withIdentifier: "Settings")
    self.present(newViewController, animated: true, completion: nil)
}

func createMenu() -> [menuItem]{
    var index: Int = 0
    for (i,image) in zip(titles, images) {
        menuItems.append(menuItem(labelText: i, picture: image, index: index))
        index += 1
    }
    return menuItems
}

}

extension MenuViewController: UITableViewDataSource, UITabBarDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menuItems.count
    }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        tableView.rowHeight = 90
        tableView.separatorStyle = .singleLine
        let item = menuItems[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell") as! MenuCell
        cell.setAttributes(item: item)
        return cell
    }
}

这是我的MenuCell代码

import UIKit

protocol SwitchView {
    func switchView(index: Int)
}

class MenuCell: UITableViewCell {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var picture: UIImageView!
var index: Int = 0
var delegate: SwitchView?

func setAttributes(item: menuItem) {
    label.text = item.labelText
    picture.image = item.picture
    index = item.index
}

@IBAction func button(_ sender: Any) {
    delegate?.switchView(index: index)
    NSLog("BUTTON")
}

}

代码运行正常,没有错误,但是当我单击表的按钮时,MenuViewController类中的switchView()方法未运行,但是按钮代码正在运行。我想念什么吗?

P.S用于选择显示哪个视图控制器的代码未运行,这时,我只是想在按下MenuCell上的按钮时显示要显示的设置视图控制器。

0 个答案:

没有答案