swift
1import UIKit 2 3class ViewController: UIViewController { 4 5 var item = String() 6 var add = UILabel() 7 //+ボタン 8 @IBAction func addlabel(_ sender: Any) { 9 10 alert() 11 //label() 12 } 13 14 //ラベルについて 15 func label(){ 16 add = UILabel(frame: CGRect(x: 130, y:250, width: 100, height:20)) 17 //ラベルの大きさ、座標指定 18 add.text = "labelです" 19 //文字を変更 20 21 add.backgroundColor = UIColor.lightGray 22 23 add.font = UIFont.systemFont(ofSize: 30) 24 //文字の大きさ 25 26 add.textColor = UIColor.black 27 //文字カラー 28 29 add.sizeToFit() 30 //文字数にあわせてlabelの大きさを変更(サイズが文字にフィットする) 31 32 self.view.addSubview(add) 33 //実際にviewに見える形でlabelが出現する 34 } 35 36 func alert(){ 37 // テキストフィールド付きアラート表示 38 39 let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert) 40 41 // OKボタンの設定 42 let okAction = UIAlertAction(title: "OK", style: .default, handler: { 43 (action:UIAlertAction!) -> Void in 44 45 // OKを押した時入力されていたテキストを表示 46 if let textFields = alert.textFields { 47 48 // アラートに含まれるすべてのテキストフィールドを調べる 49 for textField in textFields { 50 self.label() 51 self.add.text = textField.text! 52 self.add.sizeToFit() 53 print(textField.text!) 54 } 55 // UILongPressGestureRecognizerインスタンス作成 56 let longPressGesture = UILongPressGestureRecognizer(target: self, action: Selector(("longPressGesture"))) 57 //デリゲート先を自分に設定する。 58 //longPressRecognizer.delegate 59 // 時間(デフォルト0.5秒) 60 longPressGesture.minimumPressDuration = 0.5 61 self.add.isUserInteractionEnabled = true 62 self.add.addGestureRecognizer(longPressGesture) 63 } 64 }) 65 alert.addAction(okAction) 66 67 // キャンセルボタンの設定 68 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) 69 alert.addAction(cancelAction) 70 71 // テキストフィールドを追加 72 alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in 73 textField.placeholder = "テキスト" 74 }) 75 76 alert.view.setNeedsLayout() // シミュレータの種類によっては、これがないと警告が発生 77 78 // アラートを画面に表示 79 self.present(alert, animated: true, completion: nil) 80 81 } 82 83 func longpress(sender: UILongPressGestureRecognizer){ 84 85 alert() 86 } 87 override func viewDidLoad() { 88 super.viewDidLoad() 89 90 /*// UILongPressGestureRecognizerインスタンス作成 91 let longPressGesture = UILongPressGestureRecognizer(target: self, action: Selector(("longPress:"))) 92 93 // 時間(デフォルト0.5秒) 94 longPressGesture.minimumPressDuration = 1.0 95 96 add.isUserInteractionEnabled = true 97 add.addGestureRecognizer(longPressGesture)*/ 98 99 } 100 101 override func didReceiveMemoryWarning() { 102 super.didReceiveMemoryWarning() 103 // Dispose of any resources that can be recreated. 104 } 105 106 107} 108
ラベルを長押しした時にalertを呼び出す実装をしたいです。
ですが、長押しした時にalertを呼び出せずに困っています。
alert追加時に同時にlongpressの処理についても書いたの見て、実行して見たらlabelをタップした時にsignalbrtで落ちました。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/03/01 01:11