- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在我的项目中准备了以下类来检索用户当前位置:
LocationManager.swift
import Foundation
import CoreLocation
class LocationManager: NSObject {
// - Private
private let locationManager = CLLocationManager()
// - API
public var exposedLocation: CLLocation? {
return self.locationManager.location
}
override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
}
}
// MARK: - Core Location Delegate
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined : print("notDetermined") // location permission not asked for yet
case .authorizedWhenInUse : print("authorizedWhenInUse") // location authorized
case .authorizedAlways : print("authorizedAlways") // location authorized
case .restricted : print("restricted") // TODO: handle
case .denied : print("denied") // TODO: handle
default : print("unknown") // TODO: handle
}
}
}
// MARK: - Get Placemark
extension LocationManager {
func getPlace(for location: CLLocation,
completion: @escaping (CLPlacemark?) -> Void) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { placemarks, error in
guard error == nil else {
print("*** Error in \(#function): \ (error!.localizedDescription)")
completion(nil)
return
}
guard let placemark = placemarks?[0] else {
print("*** Error in \(#function): placemark is nil")
completion(nil)
return
}
completion(placemark)
}
}
}
ContentView.swift
import SwiftUI
struct Location: Identifiable {
// When conforming to the protocol Identifiable we have to to implement a variable called id however this variable does not have to be an Int. The protocol only requires that the type of the variable id is actually Hashable.
// Note: Int, Double, String and a lot more types are Hashable
let id: Int
let country: String
let state: String
let town: String
}
struct ContentView: View {
// let’s make our variable a @State variable so that as soon as we change its value (by for eexample adding new elements) our view updates automagically.
@State var locationList = [
Location(id: 0, country: "Italy", state: "", town: "Finale Emilia"),
Location(id: 1, country: "Italy", state: "", town: "Bologna"),
Location(id: 2, country: "Italy", state: "", town: "Modena"),
Location(id: 3, country: "Italy", state: "", town: "Reggio Emilia"),
Location(id: 4, country: "USA", state: "CA", town: "Los Angeles")
]
// - Constants
private let locationManager = LocationManager()
// THIS IS NOT POSSIBLE WITH SWIFTUI AND GENERATES ERRORS
guard let exposedLocation = self.locationManager.exposedLocation else {
print("*** Error in \(#function): exposedLocation is nil")
return
}
var body: some View {
// Whenever we use a List based of an Array we have to let the List know how to identify each row as unique
// When confirming to the Identifiable protocol we no longer have to explicitly tell the List how the elements in our Array (which are conforming to that protocol) are uniquely identified
NavigationView {
// let’s add a title to our Navigation view and make sure you always do so on the first child view inside of your Navigation view
List(locationList) { location in
NavigationLink(destination: LocationDetail(location: location)) {
HStack {
Text(location.country)
Text(location.town).foregroundColor(.blue)
}
}
}
.navigationBarTitle(Text("Location"))
.navigationBarItems(
trailing: Button(action: addLocation, label: { Text("Add") }))
}
}
func addLocation() {
// We are using the native .randomElement() function of an Array to get a random element. The returned element however is optional. That is because in the case of the Array being empty that function would return nil. That’s why we append the returned value only in the case it doesn’t return nil.
if let randomLocation = locationList.randomElement() {
locationList.append(randomLocation)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
最佳答案
您可以创建一个 StateObject
您的LocationManager
通过实现 ObservableObject
协议(protocol)。
与 @Published
属性,您可以创建一个发布者对象,当该对象内部发生变化时通知观察者(在这种情况下是您的 View )。
这就是为什么我在 LocationManager 中添加了 @Published
那些变量的属性:
locationStatus: CLAuthorizationStatus?
它包含从 didChangeAuthorization
收到的值委托(delegate)方法lastLocation: CLLocation?
它包含由 didUpdateLocations
计算的最后一个位置委托(delegate)方法import Foundation
import CoreLocation
import Combine
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
@Published var locationStatus: CLAuthorizationStatus?
@Published var lastLocation: CLLocation?
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
var statusString: String {
guard let status = locationStatus else {
return "unknown"
}
switch status {
case .notDetermined: return "notDetermined"
case .authorizedWhenInUse: return "authorizedWhenInUse"
case .authorizedAlways: return "authorizedAlways"
case .restricted: return "restricted"
case .denied: return "denied"
default: return "unknown"
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
locationStatus = status
print(#function, statusString)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
lastLocation = location
print(#function, location)
}
}
看法
LocationManager
的实例即可。标记为
@StateObject
import SwiftUI
struct MyView: View {
@StateObject var locationManager = LocationManager()
var userLatitude: String {
return "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"
}
var userLongitude: String {
return "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"
}
var body: some View {
VStack {
Text("location status: \(locationManager.statusString)")
HStack {
Text("latitude: \(userLatitude)")
Text("longitude: \(userLongitude)")
}
}
}
}
struct MyView_Previews: PreviewProvider {
static var previews: some View {
MyView()
}
}
关于ios - 如何在没有 ViewControllers 的情况下使用 SwiftUI 获取当前位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57681885/
有没有办法获取/获取 SwiftUI 中 Text 对象中使用的当前字体?前任。 Text("abc").font() 不起作用。 最佳答案 可以从环境访问当前字体: struct ChildView
我想知道为什么 SwiftUI 中的 2 个元素之间会出现这种间距?以及如何控制/修改它?我尝试向 ExtractedView 添加一些填充,但没有任何改变。似乎它是由 .frame(height:
目标 获取要显示在scrollView中的数据 预期结果 实际结果 另类 使用List,但不灵活(无法删除分隔符,不能具有多列) 码 struct Object: Identifiable {
我想使用 onIncrement 和 onDecrement 在手动(非绑定(bind))模式下使用 Stepper View 。当我尝试实现下限和上限时,有一种奇怪的行为,例如。年龄值不低于 1 或
我正在尝试在 SwiftUI 中显示全局警报。无论当前显示/呈现在屏幕上的内容(例如工作表),此警报都应显示在所有内容的顶部。 这是我的代码: @main struct MyApp: App {
我正在尝试为我的模态表实现一个关闭按钮,如下所示: struct TestView: View { @Environment(\.isPresented) var present va
我有一个在 SwiftUI 中处理的主细节应用程序,但是一旦在第一个 DetailView 上,NavBar 中的 NavigationLink 就不再有效。我把它写成一个简单的演示: struct
这是我想做的一个最小的、可重复的例子。 我有一系列的段落。 var notes = [ "One line paragraph", "This is a small paragraph
有什么方法可以使用 SwiftUI 找到父 View 大小,我查看了文档和示例,似乎大多数(如果不是全部)都是硬编码大小,理想情况下我想找到父 View 的大小然后设置基于父级大小百分比的 subvi
我有一个 列表由单元格组成,每个单元格包含一个图像和一列文本,我希望以特定的方式布局。左侧图像,占宽度的四分之一。文本的剩余空间,左对齐。 这是我得到的代码: struct TestCell: Vie
这是 iOS 13 Health 应用程序的屏幕截图 - 用户个人资料。我最近开始使用 swiftui并想知道如何开发如下所示的屏幕。我尝试了简单和分组的列表样式。但我无法看到下面的布局。 这样的UI
更新 : 14 个月后,AppKit 发行说明中有这样一个有趣的说明: A TextField that you are editing inside a selected List row now
我来自 React,在那里我使用 useMemo 来确保某些计算不会过于频繁地执行。我如何在 SwiftUI 中做类似的事情? 考虑这个例子: struct MyView: View { va
我已经查看并尝试了所有不同的组合,但我无法弄清楚如何更改 View 导航栏标题的文本颜色。这是我的代码,我也在尝试使用我已经从我的 Assets 文件夹中添加和使用的自定义颜色。我知道这个问题已被问过
如何更改swiftUI上导航栏“返回”按钮的文本? form from a navigationLink init(){ UINavigationBar.appearance().backgr
具有渐变填充的矩形并尝试为颜色变化设置动画。 ... Rectangle() .fill(LinearGradient( gradient: .init(stops:
我已经将UITextView包装在UIViewRepresentable中,并包括了Coordinator作为UITextViewDelegate,但是未调用事件。我究竟做错了什么? struct T
我需要更改 swiftUI 中 tabItem 徽章的颜色。我创建了这个 Pod https://github.com/jogendra/BadgeHub可以与 swiftUI 一起使用吗? 我有选项
我可以使用以下代码在 UIKIt 中定义常量字体: let appFont = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.regular)
通常我可以在 SwiftUI 中显示这样的项目列表: enum Fruit { case apple case orange case banana } struct Frui
我是一名优秀的程序员,十分优秀!