終於要進入主題,這次先來實作如何創建一個button並且開啟 camera
var window: UIWindow?
var mainVC: ViewController?
//create a window and display on the screen
window = UIWindow(frame:UIScreen.main.bounds)
//mainVC = ViewController()
//window?.rootViewController = mainVC
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
class ViewController: UIViewController ,UIImagePickerControllerDelegate, UINavigationControllerDelegate
var cameraBtn : UIButton = UIButton()
cameraBtn.frame = CGRect(x: (myFullSize.width/2 - 50), y: (myFullSize.height/2 - 30 ), width: 100 , height: 100)
cameraBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
cameraBtn.setTitle("camera", for: .normal)
cameraBtn.setTitleColor(UIColor.green, for: .normal)
cameraBtn.layer.cornerRadius = 10
cameraBtn.backgroundColor = UIColor.red
cameraBtn.addTarget(self, action: #selector(onCameraBtnAction(_:) ), for: UIControlEvents.touchUpInside)
self.view.addSubview(cameraBtn)
其中cameraBtn.addTarget(self, action: #selector(onCameraBtnAction(_:) ), for: UIControlEvents.touchUpInside)
**當按鈕被觸發(”touchUpInside”) 系統就會呼叫“onCameraBtnAction” 這個function
5. 建立一個switch,當function(“onCameraBtnAction”)經過 button被呼叫後,會去對應的 funcion(“callcamera(1)”),在這邊是檢查這個裝置是否有 camera device,如果有就會繼續執行,如果沒有就會 print (“no camera”)
func callcamera(_ cranberries:Int) {
let picker: UIImagePickerController = UIImagePickerController()
switch cranberries {
case 1:
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
picker.sourceType = UIImagePickerControllerSourceType.camera
picker.allowsEditing = true
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}else {
//print("no camera")
}
default:
print("switch default")
}
}
@objc func onCameraBtnAction(_ sender:UIButton) {
self.callcamera(1)
}
其中 “onCameraBtnAction” 因為是被 #select
所呼叫,所以前面要加上 “@objc
“才不會報錯
R.I.P
Dolores O’Riordan
1971-2018