You need to enable JavaScript to run this app. SwiftUI中@ObservedObject修饰的cameraViewModel对焦状态不更新问题求助
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中@ObservedObject修饰的cameraViewModel对焦状态不更新问题求助

SwiftUI 相机开发阻塞问题:KVO观测对焦值赋值后界面不更新
  • 开发者身份:SwiftUI开发、手动相机功能实现新手
  • 开发目标:
    • 封装UIKit相机能力为SwiftUI相机视图
    • 通过SwiftUI选择器控件控制镜头对焦位置,界面展示实时对焦数值
    • 后续实现AVCaptureDevice.lensPosition(取值范围0~1.0)与对焦选择器中物距档位的映射关联
    • 当前阶段目标:实现屏幕实时展示当前对焦数值
      核心问题:在UIViewControllerRepresentable对应的Coordinator中添加镜头对焦位置的KVO观测逻辑,将观测到的实时对焦值赋值给cameraViewModel后,界面未触发任何状态更新。

相关实现代码如下:

import SwiftUI
import AVFoundation
import Combine

struct ContentView: View {
    
    @State private var didTapCapture = false
    @State private var focusLensPosition: Float = 0
    @ObservedObject var cameraViewModel = CameraViewModel(focusLensPosition: 0)
    
    var body: some View {
        
        VStack {
            ZStack {
                CameraPreviewRepresentable(didTapCapture: $didTapCapture, cameraViewModel: cameraViewModel)
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
                
                VStack {
                    FocusPicker(selectedFocus: $focusLensPosition)
                    
                    Text(String(cameraViewModel.focusLensPosition))
                        .foregroundColor(.red)
                        .font(.largeTitle)
                }
                .frame(maxWidth: .infinity, alignment: .leading)
            }
            .edgesIgnoringSafeArea(.all)
            
            Spacer()
            
            CaptureButton(didTapCapture: $didTapCapture)
                .frame(width: 100, height: 100, alignment: .center)
                .padding(.bottom, 20)
        }
        
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct CaptureButton: View {
    @Binding var didTapCapture : Bool
    
    var body: some View {
        Button {
            didTapCapture.toggle()
            
        } label: {
            Image(systemName: "photo")
                .font(.largeTitle)
                .padding(30)
                .background(Color.red)
                .foregroundColor(.white)
                .clipShape(Circle())
                .overlay(
                    Circle()
                        .stroke(Color.red)
                )
        }
    }
}

struct CameraPreviewRepresentable: UIViewControllerRepresentable {
    
    @Environment(\.presentationMode) var presentationMode
    @Binding var didTapCapture: Bool
    @ObservedObject var cameraViewModel: CameraViewModel
    
    let cameraController: CustomCameraController = CustomCameraController()
    
    func makeUIViewController(context: Context) -> CustomCameraController {
        cameraController.delegate = context.coordinator
        
        return cameraController
    }
    
    func updateUIViewController(_ cameraViewController: CustomCameraController, context: Context) {
        
        if (self.didTapCapture) {
            cameraViewController.didTapRecord()
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self, cameraViewModel: cameraViewModel)
    }
    
    class Coordinator: NSObject, UINavigationControllerDelegate, AVCapturePhotoCaptureDelegate {
        let parent: CameraPreviewRepresentable
        var cameraViewModel: CameraViewModel
        
        var focusLensPositionObserver: NSKeyValueObservation?
        
        init(_ parent: CameraPreviewRepresentable, cameraViewModel: CameraViewModel) {
            self.parent = parent
            self.cameraViewModel = cameraViewModel
            super.init()
            
            focusLensPositionObserver = self.parent.cameraController.currentCamera?.observe(\.lensPosition, options: [.new]) { [weak self] camera, _ in

                print(Float(camera.lensPosition))
                
                //通过Publisher发布变更通知
                self?.cameraViewModel.focusLensPosition = camera.lensPosition
            }
        }
        
        deinit {
            focusLensPositionObserver = nil
        }
        
        func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
            
            parent.didTapCapture = false
            
            if let imageData = photo.fileDataRepresentation(), let image = UIImage(data: imageData) {
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
            }
            
            parent.presentationMode.wrappedValue.dismiss()
        }
    }
}

class CameraViewModel: ObservableObject {
    @Published var focusLensPosition: Float = 0

    init(focusLensPosition: Float) {
        self.focusLensPosition = focusLensPosition
    }
}

class CustomCameraController: UIViewController {
    
    var image: UIImage?
    
    var captureSession = AVCaptureSession()
    var backCamera: AVCaptureDevice?
    var frontCamera: AVCaptureDevice?
    var currentCamera: AVCaptureDevice?
    var photoOutput: AVCapturePhotoOutput?
    var cameraPreviewLayer: AVCaptureVideoPreviewLayer?
    
    //代理
    var delegate: AVCapturePhotoCaptureDelegate?
    
    func showFocusLensPosition() -> Float {
//        guard let camera = currentCamera else { return 0 }
        
//        try! currentCamera!.lockForConfiguration()
//        currentCamera!.focusMode = .autoFocus
////        currentCamera!.setFocusModeLocked(lensPosition: currentCamera!.lensPosition, completionHandler: nil)
//        currentCamera!.unlockForConfiguration()
        
        return currentCamera!.lensPosition
    }
    
    func didTapRecord() {
        
        let settings = AVCapturePhotoSettings()
        photoOutput?.capturePhoto(with: settings, delegate: delegate!)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    func setup() {
        
        setupCaptureSession()
        setupDevice()
        setupInputOutput()
        setupPreviewLayer()
        startRunningCaptureSession()
    }
    
    func setupCaptureSession() {
        captureSession.sessionPreset = .photo
    }
    
    func setupDevice() {
        let deviceDiscoverySession =
            AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera],
                                                                      mediaType: .video,
                                                                      position: .unspecified)
        for device in deviceDiscoverySession.devices {
            
            switch device.position {
            case .front:
                self.frontCamera = device
            case .back:
                self.backCamera = device
            default:
                break
            }
        }
        
        self.currentCamera = self.backCamera
    }
    
    func setupInputOutput() {
        do {
            
            let captureDeviceInput = try AVCaptureDeviceInput(device: currentCamera!)
            captureSession.addInput(captureDeviceInput)
            photoOutput = AVCapturePhotoOutput()
            captureSession.addOutput(photoOutput!)
            
        } catch {
            print(error)
        }
        
    }
    
    func setupPreviewLayer() {
        
        self.cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        self.cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        
        let deviceOrientation = UIDevice.current.orientation
        cameraPreviewLayer?.connection?.videoOrientation = AVCaptureVideoOrientation(rawValue: deviceOrientation.rawValue)!
        
        self.cameraPreviewLayer?.frame = self.view.frame
//        view.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
        self.view.layer.insertSublayer(cameraPreviewLayer!, at: 0)
    }
    
    func startRunningCaptureSession() {
        captureSession.startRunning()
    }
}


struct FocusPicker: View {
    
    var feets = ["∞ ft", "30", "15", "10", "7", "5", "4", "3.5", "3", "2.5", "2", "1.5", "1", "0.5", "Auto"]
    
    @Binding var selectedFocus: Float
    
    var body: some View {
        
        Picker(selection: $selectedFocus, label: Text("")) {
            ForEach(0..<feets.count) {
                Text(feets[$0])
                    .foregroundColor(.white)
                    .font(.subheadline)
                    .fontWeight(.medium)
                
            }
            .animation(.none)
            .background(Color.clear)
            .pickerStyle(WheelPickerStyle())
        }
        .frame(width: 60, height: 200)
        .border(Color.gray, width: 5)
        .clipped()
    }
}

内容的提问来源于stack exchange,提问作者ViOS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.18 22:06:03