ボタンをタップした後にカメラを開くUIBarButtonItemを作成しようとしています。何らかの理由で、私のtakePicture(_sender :)関数が呼び出されていないようです。UIBarButtonItemがIBActionをトリガーしない
私はもともとInterface Builderを使用してUIBarButtonItemを作成しようとしました。ここではインタフェースとUIBarButtonItemに接続されたアクションのスクリーンショットでした:
は、そして、ここで私のtakePictureのためのコード(_sender :)関数である:
@IBAction func takePicture(_ sender: UIBarButtonItem) {
print("Taking picture...")
let imagePicker = UIImagePickerController()
// If the device has a camera, take a picture; otherwise,
// just pick from photo library
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePicker.sourceType = .camera
} else {
imagePicker.sourceType = .photoLibrary
}
imagePicker.delegate = self
// Place image picker on the screen
present(imagePicker, animated: true, completion: nil)
}
小さな円が関数宣言の横に記入して正しく接続してください。
しかし、シミュレータをロードしてボタンを押すと、UIImagePickerControllerが表示されず、my print()関数がコード内で呼び出されることはありません。
それで、UIBarButtonItemをプログラムで宣言して、XcodeのInterface Builderの問題であるかどうかを確認しようとしました。これをデバッグで土壇場の試みとして
override func viewDidLoad() {
super.viewDidLoad()
let takePictureBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.camera, target: self, action: #selector(DetailViewController.takePicture))
toolBar.setItems([takePictureBarButton], animated: false)
}
@objc func takePicture() {
print("Taking picture...")
let imagePicker = UIImagePickerController()
// If the device has a camera, take a picture; otherwise,
// just pick from photo library
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePicker.sourceType = .camera
} else {
imagePicker.sourceType = .photoLibrary
}
imagePicker.delegate = self
// Place image picker on the screen
present(imagePicker, animated: true, completion: nil)
}
:
(私はInterface BuilderのからUIBarButtonItemを削除してから、私は@IBOutletを使用して私のコードにUIToolbarを接続注:。)ここに私のコードでしたプログラムで問題がどこにあるのかを調べるために、UIに一時的なボタンを作成し、代わりにtakePicture(_sender :)関数に接続しました(UIBarButtonItemからUIButtonにシグネチャを変更しました)。それは完璧に働いた。これは、問題は機能そのものではなく、接続と関係があることを示しています。
のアクションであなたのカメラボタンを接続することを確認し、そのアドバイスの貴重な作品となりそうです。ただし、UIBarButtonItemにはtouchUpInsideイベントがありません。 UIBarButtonItemは、NSObjectのサブクラスであるUIBarItemのサブクラスです。UIButtonは、すべてのtouchUpInside()アクションを含むUIControlのサブクラスです。 より慎重にマニュアルを確認することがあります: - https://developer.apple.com/documentation/uikit/uicontrolevents - https://developer.apple.com/documentation/uikit/uibaritem - HTTPS: //developer.apple.com/documentation/uikit/uibarbuttonitem – Mattkx4