ios - 如何在另一个 .swift 文件中调用变量属性?

标签 ios swift variables swift3 xcode8

我将在我的 2 个 .swift 文件的第 2 部分代码下方发布:

Master .swift(部分代码)

import UIKit
import AVFoundation
import PageMenu
import SwiftyCam




class randomController: SwiftyCamViewController, SwiftyCamViewControllerDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate, CAPSPageMenuDelegate, AVCapturePhotoCaptureDelegate   {



    @IBOutlet weak var cameraPreview: UIImageView!
    @IBOutlet weak var backgroundImage: UIImageView!

    let preview: PreviewView = {
        let pv = PreviewView()
        pv.cameraPreviewFrame = cameraPreview.bounds
        return pv
    }()

    @IBAction func cameraButton(_ sender: Any) {




    }


    @IBOutlet weak var backgroundMarrone: UIImageView!

    func askPermission() {
        print("here")
        let cameraPermissionStatus =  AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)

        switch cameraPermissionStatus {
        case .authorized:
            print("Already Authorized")
        case .denied:
            print("denied")

            let alert = UIAlertController(title: "Sorry :(" , message: "But  could you please grant permission for camera within device settings",  preferredStyle: .alert)
            let action = UIAlertAction(title: "Ok", style: .cancel,  handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)

        case .restricted:
            print("restricted")
        default:
            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: {
                [weak self]
                (granted :Bool) -> Void in

                if granted == true {
                    // User granted
                    print("User granted")
                    DispatchQueue.main.async(){
                        //Do smth that you need in main thread
                    }
                }
                else {
                    // User Rejected
                    print("User Rejected")

                    DispatchQueue.main.async(){
                        let alert = UIAlertController(title: "WHY?" , message:  "Camera it is the main feature of our application", preferredStyle: .alert)
                        let action = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
                        alert.addAction(action)
                        self?.present(alert, animated: true, completion: nil)  
                    } 
                }
            });
        }
    }
    @IBOutlet weak var cameracapture: UIImageView!
    var pageMenu : CAPSPageMenu?



    @IBAction func cameraCaptureButton(_ sender: Any) {
    takePhoto()
}

    var flashButton = UIButton()

        override func viewDidLoad() {
        super.viewDidLoad()
            cameraDelegate = self
                pageMenu?.delegate = self


        var controllerArray : [UIViewController] = []

        backgroundMarrone.frame = CGRect(x: 0, y:(view.frame.maxY/10*5), width: self.view.frame.width, height: self.view.frame.height )

        cameraPreview.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: backgroundMarrone.frame.minY  )


            let switchCameraButton = UIButton(frame: CGRect(x: 5, y: cameraPreview.frame.maxY/12*9.8, width: 50, height: 50))
            switchCameraButton.backgroundColor = UIColor(red: 100.0/255.0, green: 39.0/255.0, blue: 87.0/255.0, alpha: 0.0)
            switchCameraButton.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside)
            switchCameraButton.setImage(#imageLiteral(resourceName: "btn_reverse_camera copy.png"), for: UIControlState.normal)
            self.view.addSubview(switchCameraButton)

            flashButton = UIButton(frame: CGRect(x: cameraPreview.frame.maxX - 55, y: cameraPreview.frame.maxY/12*9.8, width: 50, height: 50))
            flashButton.backgroundColor = UIColor(red: 100.0/255.0, green: 39.0/255.0, blue: 87.0/255.0, alpha: 0.0)
            flashButton.addTarget(self, action: #selector(pressButton1(button:)), for: .touchUpInside)
            flashButton.setImage(#imageLiteral(resourceName: "btn_flash copy.png"), for: UIControlState.normal)
            self.view.addSubview(flashButton)




        let libraryController : UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "libraryController") as! libraryController
            libraryController.title = "Libreria"
            controllerArray.append(libraryController)


            let photoController : UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "photoController") as! photoController
            photoController.title = "Foto"
            controllerArray.append(photoController)



        let videoController : UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "videoController") as! videoController
        videoController.title = "Video"
        controllerArray.append(videoController)

        let parameters: [CAPSPageMenuOption] = [
            .menuItemSeparatorWidth(0),
            .useMenuLikeSegmentedControl(true),
            .menuItemSeparatorPercentageHeight(0.1),
            .centerMenuItems (true)
        ]

        pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0, y: cameraPreview.frame.maxY , width: self.view.frame.width, height: view.frame.height ), pageMenuOptions: parameters)

        self.view.addSubview(pageMenu!.view)

        }
var ciaone = false



    override func viewWillAppear(_ animated: Bool) {








        }


    func beginSession(captureDevice : AVCaptureDevice?) {

        ciaone = false



        }






    var a = 0
    func pressButton(button: UIButton) {

        if (a == 0) {
            print("dioschifoso!")
            beginSession(captureDevice: AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo))

            a = 1

        } else {

            beginSession(captureDevice: AVCaptureDevice.defaultDevice(withDeviceType: AVCaptureDeviceType.builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.front))


            a = 0

        }
    }
    var flash = 0




    func toggleTorch(on: Bool) {
        //guard let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else { return }
        /*
        if device.hasTorch {
            do {
                try device.lockForConfiguration()

                if on == true {
                    device.torchMode = .on
                } else {
                    device.torchMode = .off
                }

                device.unlockForConfiguration()
            } catch {
                print("Torch could not be used")
            }
        } else {
            print("Torch is not available")
        }
 */

    }


    func pressButton1(button: UIButton) {
        /*
        if (a == 0) {
                 //toggleTorch(on: true)
            flashButton.setImage(#imageLiteral(resourceName: "btn_flash_off.png"), for: UIControlState.normal)


            a = 1

        } else {


            //toggleTorch(on: false)
            flashButton.setImage(#imageLiteral(resourceName: "btn_flash copy.png"), for: UIControlState.normal)
            a = 0

        }
       */
///////Annullo momentaneamente il codice per switch flash
/*
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        if (device?.hasTorch)! && (device?.hasFlash)! {
            do {
                try device?.lockForConfiguration()
            } catch {
                // handle error
                return
            }

            device?.focusMode = .continuousAutoFocus
            device?.flashMode = .auto
            if device?.torchMode == .auto {

                device?.torchMode = .on
                device?.flashMode = .on
                flashButton.setImage(#imageLiteral(resourceName: "btn_flash_off.png"), for: UIControlState.normal)
            }
            else if device?.torchMode == .on {
                device?.torchMode = .off
                device?.flashMode = .off
                 flashButton.setImage(#imageLiteral(resourceName: "btn_flash copy.png"), for: UIControlState.normal)
            }
            else {
                device?.torchMode = .auto
                device?.flashMode = .auto
            }

            device?.unlockForConfiguration()
        }
 */

 takePhoto()

 }
    func swiftyCam(_ swiftyCam: SwiftyCamViewController, didTake photo: UIImage) {
        // Called when takePhoto() is called or if a SwiftyCamButton initiates a tap gesture
        // Returns a UIImage captured from the current session
        let newVC = photoViewController(image: photo)
        self.present(newVC, animated: true, completion: nil)


    }






    func capturePicture(){


        }






    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

二次.swift(完整代码)

import UIKit
import AVFoundation



class PreviewView: UIView {


    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.black
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }


    var videoPreviewLayer: AVCaptureVideoPreviewLayer {
        self.videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

        self.videoPreviewLayer.frame = randomController
        return layer as! AVCaptureVideoPreviewLayer

    }

    var session: AVCaptureSession? {
        get {
            return videoPreviewLayer.session
        }
        set {
            videoPreviewLayer.session = newValue
        }
    }

    // MARK: UIView

    override class var layerClass : AnyClass {
        return AVCaptureVideoPreviewLayer.self
    }
}

现在,在我的辅助 .swift 中,我需要设置 videoPreviewLayer.frame = cameraPreview.bounds 。变量 cameraPreview 位于 Master .swift 中。 我如何使用尽可能少的代码来做到这一点?我已经尝试创建一个 let "something"并将其设置为 =randomController() 但会弹出一个错误并告诉我“使用未解析的标识符”。 在此先感谢您的帮助,如果我不清楚什么可以问我。

最佳答案

将您的辅助 .swift 更改为:

import UIKit
import AVFoundation



class PreviewView: UIView {


    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.black
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var cameraPreviewFrame: CGRect? {  // declare new variable
        didSet { 
            videoPreviewLayer.frame = cameraPreviewFrame
        }
    }

    var videoPreviewLayer: AVCaptureVideoPreviewLayer {
        self.videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        // this line was deleted: self.videoPreviewLayer.frame = randomController
        return layer as! AVCaptureVideoPreviewLayer

    }

    var session: AVCaptureSession? {
        get {
            return videoPreviewLayer.session
        }
        set {
            videoPreviewLayer.session = newValue
        }
    }

    // MARK: UIView

    override class var layerClass : AnyClass {
        return AVCaptureVideoPreviewLayer.self
    }
}

根据@Tj3n 的建议更新:

然后将您的Master .swift:

lazy var preview: PreviewView = {
    let pv = PreviewView()
    pv.cameraPreviewFrame = self.cameraPreview.bounds
    return pv
}()

关于ios - 如何在另一个 .swift 文件中调用变量属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42646736/

相关文章:

ios - 无法使用 NSUserDefaults 保存整数

ios - Pod 规范验证 Cocoa Pod 问题

ios - UINavigationController titleView 中的 UISearchBar 没有响应/可点击

java - 动态更新 fragment 调用

objective-c - 创建具有向前和向后导航的模拟 3D "space"

iOS DropboxSDK [警告] - ( 400 )

ios - swift3 从空投中接受一个文件

swift - 用于将便捷构造函数添加到核心数据库中的通用函数

java - 尝试返回一个无法解析为变量的变量

java - Jmeter 和全局 Beanshell 变量