我将在我的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()但是会弹出一个错误并告诉我“使用未解析的标识符”。 提前感谢您的帮助,如果我不清楚某事请问我。
答案 0 :(得分:1)
将 辅助.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
}()