MKMapView的比例未显示

问题描述 投票:4回答:2

我正在做一个iOS应用程序。在Xcode 9.1中,我创建了一个MKMapView

let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
mapView.isUserInteractionEnabled = false
mapView.mapType = .satellite
mapView.showsCompass = false
mapView.showsScale = true
view.addSubview(mapView)

但是当我在模拟器中运行它时,比例没有显示,我在日志中收到三条消息:

无法从边缘9插入罗盘

无法从边缘9插入比例

无法在角落4处插入法律归属

罗盘未显示(如预期的那样),但如果我将mapView.showsCompass更改为truee,则不会显示。但是,会显示法律链接。我在这里错过了什么?我猜它是关于iOS 11引入的新安全区域的一些东西,但是我没有看到这对于我希望覆盖整个屏幕的视图是多么重要。

ios swift mkmapview
2个回答
7
投票

在iOS 10或更低版本中

正如@ Paulw11所说,缩放仅在默认缩放时显示。

在iOS 11中

你可以使用scaleVisibilityhttps://developer.apple.com/documentation/mapkit/mkscaleview/2890254-scalevisibility

let scale = MKScaleView(mapView: mapView)
scale.scaleVisibility = .visible // always visible
view.addSubview(scale)

3
投票

今天的规模也有同样的问题。我希望这个比例始终可见。花费我几个小时来解决它。所以我在这里添加代码,以防万一有人遇到同样的问题。

得到一些提示:

来自这个主题:Use Safe Area Layout programmatically

和这个网站:Pain Free Constraints with Layout Anchors

快乐的编码......

哈迪

// "self.MapOnScreen" refers to the map currently displayed

// check if we have to deal with the scale
if #available(iOS 11.0, *) {

    // as we will change the UI, ensure it's on main thread
    DispatchQueue.main.async(execute: {

        // switch OFF the standard scale (otherwise both will be visible when zoom in/out)
        self.MapOnScreen.showsScale = false

        // build the view
        let scale = MKScaleView(mapView: self.MapOnScreen)

        // we want to use autolayout
        scale.translatesAutoresizingMaskIntoConstraints = false

        // scale should be visible all the time
        scale.scaleVisibility = .visible // always visible

        // add it to the map
        self.MapOnScreen.addSubview(scale)

        // get the current safe area of the map
        let guide = self.MapOnScreen.safeAreaLayoutGuide

        // Activate this array of constraints, which at the time removes leftovers if any
        NSLayoutConstraint.activate(
            [
                // LEFT (I do not want a change if right-to-left language) margin with an offset to safe area
                // alternative would be ".leadingAnchor", which switches to the right margin, if right-to-left language is used        
                scale.leftAnchor.constraint(equalTo: guide.leftAnchor, constant: 16.0),

                // right edge will be the middle of the map
                scale.rightAnchor.constraint(equalTo: guide.centerXAnchor),

                // top margin is the top safe area
                scale.topAnchor.constraint(equalTo: guide.topAnchor),

                // view will be 20 points high
                scale.heightAnchor.constraint(equalToConstant: 20.0)
            ]
        )
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.