변수가 변경될 때 SwiftUI의 View가 다시 로드되도록 합니다.
                                            
                                                
                                                
                                                
                                                
                                                
                                                 12703 단어  SwiftUI
                    
@State @Binding @Published 이 기사에서는 이러한 변수 유형을 소개합니다.
@State
@State 변수를 변경하면 해당 뷰가 자동으로 업데이트됩니다.
struct ContentView: View {
    @State var textContent = "Loading..."
    var body: some View {
        Text(textContent)
            .padding()
            .onAppear(perform: {
                Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in
                    self.textContent = "Hello world!"
                }
            })
    }
}
 @Binding
뷰 오브젝트가 많은 서브뷰로 분할되는 경우, 서브뷰에는 @Binding 속성을 정의할 수 있고, 기본 뷰에는 @State 변수를 정의할 수 있습니다.
struct ContentView_SubView: View {
    @Binding private var textContent: String
    init(textContent: Binding<String>) {
        _textContent = textContent
    }
    var body: some View {
        Text(textContent)
            .padding()
    }
}
struct ContentView: View {
    @State var textContent = "Loading..."
    var body: some View {
        ContentView_SubView(textContent: $textContent)
            .onAppear(perform: {
                Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in
                    self.textContent = "Hello world!"
                }
            })
    }
}
 @ObservedObject and @Published
예를 들어 SwiftUI의 뷰에 사용자의 위치를 표시하려면 도우미 클래스 LocationHelper를 작성할 수 있습니다.
LocationHelper는 CLLocationManager에서 위치를 검색하고 변수 userCoordinate에 좌표를 저장합니다.
ObservableObject 프로토콜을 준수하기 위해 LocationHelper를 설정하고 속성 래퍼에 @Published를 갖도록 userCoordinate를 설정할 수 있습니다.
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Published var userLocation: CLLocation?
    let locationManager = CLLocationManager()
    init(accuracy: CLLocationAccuracy) {
        super.init()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = accuracy
        self.locationManager.requestAlwaysAuthorization()
        self.locationManager.startUpdatingLocation()
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        self.userLocation = location
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
}
SwiftUI 뷰에서 LocationManager에 @ObservedObject를 추가 할 수 있습니다.
@ObservedObject var location: LocationManager
init() {
    self.location = LocationManager(accuracy: kCLLocationAccuracyNearestTenMeters)
}
그리고 변수의 변화를 모니터링하기 위해 함수 .onChange를 사용할 수 있습니다.
struct ContentView: View {
    @ObservedObject var location: LocationManager
    init() {
        self.location = LocationManager(accuracy: kCLLocationAccuracyNearestTenMeters)
    }
    var body: some View {
        Form {
            // TODO
        }
        .onChange(of: self.location.userLocation, perform: { value in
            if let receivedUpdate = value {
                self.locationsRecorded.append(locationEntry(timeStamp: receivedUpdate.timestamp, coordinate: receivedUpdate.coordinate))
            }
        })
    }
}
  트위터 @MszPro
 트위터 @MszPro
  내 게시된 Qiita 기사 목록을 카테고리별로 확인할 수 있습니다.
 내 게시된 Qiita 기사 목록을 카테고리별로 확인할 수 있습니다.
  
                
                    
        
    
    
    
    
    
                
                
                
                
                    
                        
                            
                            
                            Reference
                            
                            이 문제에 관하여(변수가 변경될 때 SwiftUI의 View가 다시 로드되도록 합니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
                                
                                https://qiita.com/MaShunzhe/items/cb45b5607fa586f6c442
                            
                            
                            
                                텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            
                                
                                
                                 우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
                            
                        
                    
                
                
                
            
struct ContentView: View {
    @State var textContent = "Loading..."
    var body: some View {
        Text(textContent)
            .padding()
            .onAppear(perform: {
                Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in
                    self.textContent = "Hello world!"
                }
            })
    }
}
뷰 오브젝트가 많은 서브뷰로 분할되는 경우, 서브뷰에는
@Binding 속성을 정의할 수 있고, 기본 뷰에는 @State 변수를 정의할 수 있습니다.struct ContentView_SubView: View {
    @Binding private var textContent: String
    init(textContent: Binding<String>) {
        _textContent = textContent
    }
    var body: some View {
        Text(textContent)
            .padding()
    }
}
struct ContentView: View {
    @State var textContent = "Loading..."
    var body: some View {
        ContentView_SubView(textContent: $textContent)
            .onAppear(perform: {
                Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { _ in
                    self.textContent = "Hello world!"
                }
            })
    }
}
@ObservedObject and @Published
예를 들어 SwiftUI의 뷰에 사용자의 위치를 표시하려면 도우미 클래스 LocationHelper를 작성할 수 있습니다.
LocationHelper는 CLLocationManager에서 위치를 검색하고 변수 userCoordinate에 좌표를 저장합니다.
ObservableObject 프로토콜을 준수하기 위해 LocationHelper를 설정하고 속성 래퍼에 @Published를 갖도록 userCoordinate를 설정할 수 있습니다.
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Published var userLocation: CLLocation?
    let locationManager = CLLocationManager()
    init(accuracy: CLLocationAccuracy) {
        super.init()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = accuracy
        self.locationManager.requestAlwaysAuthorization()
        self.locationManager.startUpdatingLocation()
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        self.userLocation = location
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
}
SwiftUI 뷰에서 LocationManager에 @ObservedObject를 추가 할 수 있습니다.
@ObservedObject var location: LocationManager
init() {
    self.location = LocationManager(accuracy: kCLLocationAccuracyNearestTenMeters)
}
그리고 변수의 변화를 모니터링하기 위해 함수 .onChange를 사용할 수 있습니다.
struct ContentView: View {
    @ObservedObject var location: LocationManager
    init() {
        self.location = LocationManager(accuracy: kCLLocationAccuracyNearestTenMeters)
    }
    var body: some View {
        Form {
            // TODO
        }
        .onChange(of: self.location.userLocation, perform: { value in
            if let receivedUpdate = value {
                self.locationsRecorded.append(locationEntry(timeStamp: receivedUpdate.timestamp, coordinate: receivedUpdate.coordinate))
            }
        })
    }
}
  트위터 @MszPro
 트위터 @MszPro
  내 게시된 Qiita 기사 목록을 카테고리별로 확인할 수 있습니다.
 내 게시된 Qiita 기사 목록을 카테고리별로 확인할 수 있습니다.
  
                
                    
        
    
    
    
    
    
                
                
                
                
                    
                        
                            
                            
                            Reference
                            
                            이 문제에 관하여(변수가 변경될 때 SwiftUI의 View가 다시 로드되도록 합니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
                                
                                https://qiita.com/MaShunzhe/items/cb45b5607fa586f6c442
                            
                            
                            
                                텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            
                                
                                
                                 우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
                            
                        
                    
                
                
                
            
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Published var userLocation: CLLocation?
    let locationManager = CLLocationManager()
    init(accuracy: CLLocationAccuracy) {
        super.init()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = accuracy
        self.locationManager.requestAlwaysAuthorization()
        self.locationManager.startUpdatingLocation()
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        self.userLocation = location
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
}
@ObservedObject var location: LocationManager
init() {
    self.location = LocationManager(accuracy: kCLLocationAccuracyNearestTenMeters)
}
struct ContentView: View {
    @ObservedObject var location: LocationManager
    init() {
        self.location = LocationManager(accuracy: kCLLocationAccuracyNearestTenMeters)
    }
    var body: some View {
        Form {
            // TODO
        }
        .onChange(of: self.location.userLocation, perform: { value in
            if let receivedUpdate = value {
                self.locationsRecorded.append(locationEntry(timeStamp: receivedUpdate.timestamp, coordinate: receivedUpdate.coordinate))
            }
        })
    }
}
Reference
이 문제에 관하여(변수가 변경될 때 SwiftUI의 View가 다시 로드되도록 합니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/MaShunzhe/items/cb45b5607fa586f6c442텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)