自定义UIMenuController不显示Swift 4

时间:2018-09-26 22:03:06

标签: ios swift menu uimenucontroller uimenuitem

我试图用几个UIMenuItems创建一个自定义UIMenuController。我正在UITableViewCell子类中实现此功能。我尝试使用以下代码创建自定义UIMenuController。当我点击并按住表格单元格时,仅显示“复制”菜单项。但是,菜单1将不会显示。我想念什么?

override func awakeFromNib() {
    super.awakeFromNib()
    self.tableView.delegate = self
    self.tableView.dataSource = self
    tableView.reloadData()

    let myMenuController: UIMenuController = UIMenuController.shared

    // make menu visible on MenuController
    myMenuController.isMenuVisible = true

    // set the arrow down.
    myMenuController.arrowDirection = UIMenuControllerArrowDirection.down

    // set rect、view
    myMenuController.setTargetRect(CGRect.zero, in: self.tableView)

    // make MenuItems
    let myMenuItem_1: UIMenuItem = UIMenuItem(title: "Menu1", action: #selector(onMenu1(sender:)))
    let myMenuItem_2: UIMenuItem = UIMenuItem(title: "Menu2", action: #selector(onMenu2(sender:)))
    let myMenuItem_3: UIMenuItem = UIMenuItem(title: "Menu3", action: #selector(onMenu3(sender:)))

    // make an array to store MenuItems
    let myMenuItems: NSArray = [myMenuItem_1, myMenuItem_2, myMenuItem_3]

    // add MenuItems to MenuController
    myMenuController.menuItems = myMenuItems as? [UIMenuItem]
    // Initialization code
}

@objc func onMenu1(sender: UIMenuItem) {
    print("onMenu1")
}
@objc func onMenu2(sender: UIMenuItem) {
    print("onMenu2")
}
@objc func onMenu3(sender: UIMenuItem) {
    print("onMenu3")
}

func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
    return true
}
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
    print(action)
    print(#selector(onMenu1(sender:)))
    return action == #selector(onMenu1(sender:)) || action == #selector(copy(_:))
}
override func becomeFirstResponder() -> Bool {
    return true
}
override var canBecomeFirstResponder: Bool {
    return true
}

0 个答案:

没有答案