2017-06-26 17 views
1

UIViewには、複数のUILabelがあります。今、UIViewがクリックされたときに警告を追加したいと思います。ビューのクリックイベントは可能ですか?UIViewのタッチ後の警告

class viewController: UIViewController { 


@IBOutlet weak var view1: UIView! 
@IBOutlet weak var view2: UIView! 
@IBOutlet weak var view3: UIView! 

override func viewDidLoad() { 
    super.viewDidLoad() 
} 

func action(_ sender: UIView) { 
    // Create the alert controller 
    let alertController = UIAlertController(title: "title", message: "message", preferredStyle: .alert) 

    // Create the actions 
    let okAction = UIAlertAction(title: "title", style: UIAlertActionStyle.default) { 
    } 

    // Add the actions 
    alertController.addAction(okAction) 

    // Present the controller 
    self.present(alertController, animated: true, completion: nil) 
} 

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

actionは私の例のようになります機能:私の未完成のコードザッツ

。今私はそれを呼び出す方法を知ってそれを参照する必要がありますUIView

答えて

1

はい。あなたのviewDidLoaeでは、silenter

let gesture = UITapGestureRecognizer(target: self, action: #selector (viewClicker(sender:))) 
self.view1.addGestureRecognizer(gesture) 

を追加し、この機能に

func viewClicker(sender : UITapGestureRecognizer) { 
    // Do what you want 
} 
1

スウィフト3.0

をあなたのクリックアクションをキャッチあなたはこのクリックイベントのアウトレットを作成する必要はありません。これを達成するには、overridingtouchesBegantagを設定してビューを再認定します。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

    let touchView = touches.first 

    if let tag = touchView?.view?.tag{ 
     switch tag { 
     case 1: 
      self.ShowAlert(message: "Orange") //view1.tag = 1 
     case 2: 
      self.ShowAlert(message: "Red") //view2.tag = 2 
     case 3: 
      self.ShowAlert(message: "Green") //view3.tag = 3 
     default: 
      break 
     } 

    } 
} 

private func ShowAlert(message:String){ 

    print(message) 
} 

OUTPUT: -

enter image description here

+0

ありがとうございました。しかし、私はビューの数を取得していない、すべての 'タグ'は0 – j10

+0

@ j10の値を持っています。あなたは直接代わりにUiViewをチェックすることができますあなたはtag.checkの代わりにチェックすることができます –

+0

@全てのオブジェクトは 'tag'を' 0'としています。あなたが望むなら、 'Storyboard'に' tag'を設定することができます –

1

特定のコントロールをクリックしたときだけ、あなたがtouchesBeganメソッドをオーバーライドすることができます。タグを確認する代わりに、直接UIViewを比較できます

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    if let touch = touches.first { 
     switch touch.view? { 
      case self.view1: 
         // show alert 
         break 
      case self.view2: 
         // show alert 
         break 
      case self.view3: 
         // show alert 
         break 
      default: 
        break 
     } 

    } 
} 
関連する問題