点击MKAnnotationView时显示UIMenuController

时间:2018-01-16 13:00:30

标签: ios swift

这就是我在代码中所做的:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    print("selectedview")

    let controller = UIMenuController.shared
    let item = UIMenuItem(title: "Usun", action: #selector(deletePointer))
    controller.menuItems = [item]
    controller.setTargetRect(mapView.frame, in: mapView)
    controller.setMenuVisible(true, animated: true)
}

@objc func deletePointer() {
    print("deleted")
}

但不显示菜单。调用方法是因为打印了selectedView

enter image description here

2 个答案:

答案 0 :(得分:1)

您的ViewController必须能够成为第一个响应者:

class TableModel(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        super(TableModel, self).__init__()
        self.datatable = None

    def update(self, dataIn):
        print ('Updating Model')
        self.datatable = dataIn

    def rowCount(self, parent=QModelIndex()):
        return len(self.datatable.index) if self.datatable else 0

    def columnCount(self, parent=QModelIndex()):
        return len(self.datatable.columns.values) if self.datatable else 0

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            i = index.row()
            j = index.column()
            return '{0}'.format(self.datatable.iget_value(i, j))
        else:
            return QVariant()

    def flags(self, index):
        return Qt.ItemIsEnabled

if __name__ == '__main__':
    import sys

    myApp = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    tablemodel=TableModel()
    engine.rootContext().setContextProperty('PersonModel', tablemodel)
    engine.load(QUrl.fromLocalFile(QDir.current().absoluteFilePath('main.qml')))
    if len(engine.rootObjects()) == 0:
        sys.exit(-1)
    sys.exit(myApp.exec_())

然后像这样设置目标rect(其中override func canBecomeFirstResponder() -> Bool { return true } 是annotationView):

view

很抱歉我的代码是Swift 2代码......:)

答案 1 :(得分:0)

对于Swift 5.0,应该是:

extension  mapViewController
{

// Your View Controller
override var canBecomeFirstResponder: Bool
{
    return true
}


func mapView(_ mapView: MKMapView, didSelect annoView: MKAnnotationView )
{
    let controller = UIMenuController.shared
    let item = UIMenuItem(title: "Menu Test1", action: #selector(menuTestFunc))
    controller.menuItems = [item]

    if #available(iOS 13.0, *)
    {
        UIMenuController.shared.showMenu( from: self.view, rect: annoView.frame )
    }
    else
    {
        UIMenuController.shared.setTargetRect( annoView.frame, in: self.view )
        UIMenuController.shared.setMenuVisible( true, animated: true )
    }
}


@objc func menuTestFunc()
{
    print( "menuTestFunc() called" )
}

} //    mapViewController extensions