【问题标题】:Update UILabel.text with Coordinates使用坐标更新 UILabel.text
【发布时间】:2017-05-26 07:27:59
【问题描述】:

我正在尝试在主从应用程序的详细视图中显示两个标签。我希望第一个标签显示“餐厅名称”,第二个标签显示“用户当前位置”。我已经成功实现了“locationManager”,并且在我的控制台中获得了正确的当前用户坐标。但是,我想在标签的文本中显示坐标。我认为以下代码的问题是第二个标签在接收到坐标之前设置。实施它的最佳方法是什么?

func configureView() {

//to display label with restaurant name
    if let restaurant = self.restaurant {
        if let label = self.restaurantNameLabel {
            label.text = restaurant.RestaurantName
        }
    }

 //to display label with user's Latitude and Longitude:

    if let label = self.CurrentLocation {
        label.text = "\(currentLocation?.longitude)"
    }  
}

我也有 didSet 方法:

var restaurant: Restaurant? {
    didSet {
        self.configureView()
     }
}

var currentLocation: Coordinate? {
    didSet {
        self.configureView()
    }
}

【问题讨论】:

    标签: ios user-interface swift3 uilabel cllocationmanager


    【解决方案1】:

    首先,我建议将Restaurant 类中的RestaurantName 属性重命名为name,将UILabel CurrentLocation 重命名为currentLocationLabel。其次,在其各自的didSet 块中配置属性的相应标签会更简单。另外,我使用了flatMap - 在currentLocation 的情况下,如果为 nil,将返回 nil - 否则, currentLocation 将被闭包操作并返回。

    var restaurant: Restaurant? {
        didSet {
            restaurantNameLabel?.text = restaurant.flatMap { $0.name }
        }
    }
    
    var currentLocation: Coordinate? {
        didSet {
            currentLocationLabel?.text = currentLocation.flatMap { "\($0.latitude), \($0.longitude)" }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      相关资源
      最近更新 更多