简体   繁体   中英

Update UILabel.text with Coordinates

I am trying to display two labels in a detail view of master-detail app. I want the first label to display 'restaurant name' and the second label 'users current location'. I have successfully implemented `locationManager' and I get correct current user's coordinates in my console. However, I would like to display the coordinates in the text of the label. I assume that the problem why the following code is that the second label sets up before the coordinates are received. What would be the best thing to implement it?

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)"
    }  
}

I also have didSet methods:

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

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

Firstly, I suggest renaming the RestaurantName property in the Restaurant class to just name and the UILabel CurrentLocation to currentLocationLabel . Secondly, it would be simpler to configure the property's corresponding label in it's respective didSet block. Also, I have used flatMap - which in the case of currentLocation if nil, will return nil - otherwise, the currentLocation will be manipulated and returned by the closure.

var restaurant: Restaurant? {
    didSet {
        restaurantNameLabel?.text = restaurant.flatMap { $0.name }
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM