์ƒˆ์†Œ์‹

๐Ÿ“ฑ iOS/-- UIKit

(iOS) UIControl ๊ณตํ†ต ๊ฐœ๋… - Target Action , selector

  • -

UIControl ์˜ ์ข…๋ฅ˜

  • Button
  • Switch
  • Slider
  • Page Control
  • Date Picker
  • Segmented Control
  • Stepper

 

UIControl & Taget-Action

  • UIControl์€ UIView์˜ ํ•˜์œ„ํด๋ž˜์Šค์ด๋ฉฐ, ๊ทธ ๋ฐ‘์— UIButton, UISwitch... ๋“ฑ์˜ ์ปจํŠธ๋กค๋“ฑ์ด ์กด์žฌํ•œ๋‹ค.
  • ์ปจํŠธ๋กค๋“ค์€ ์‚ฌ์šฉ์ž์˜ ํ„ฐ์น˜(์ด๋ฒคํŠธ)์— ๋”ฐ๋ผ Target-Action ๋งค์ปค๋‹ˆ์ฆ˜์œผ๋กœ ๋™์ž‘ํ•˜๊ฒŒ ๋œ๋‹ค.
  • Target ์ง€์ •์€ addTarget(_:action:for:) ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

 

์•ก์…˜ ๋ฉ”์†Œ๋“œ๋Š” ์„ธ๊ฐ€์ง€ ํ˜•์‹์ด ์žˆ๋‹ค.

@IBAction func doSomething()
@IBAction func doSomething(sender : UIButton)
@IBAction func doSomething(sender : UIButton, forEvent event : UIEvent)

 

์ปจํŠธ๋กค์— ํ•ด๋‹นํ•˜๋Š” sender๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ์—ญํ• ์„ ํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ด๋ฒคํŠธ ํŒŒ๋ผ๋ฏธํ„ฐ์— ํ•ด๋‹นํ•˜๋Š” UIEvent ๊ฐ์ฒด๋Š” ์ด๋ฒคํŠธ์˜ ํŠธ๋ฆฌ๊ฑฐ๊ฐ€ ๋œ๋‹ค.

import UIKit

class UIViewController { 
}

 

 

Selector ์™€ addTarget ์„ ์‚ฌ์šฉํ•˜์—ฌ target ์—ฐ๊ฒฐ ์˜ˆ์ œ

(์Šคํ† ๋ฆฌ ๋ณด๋“œ์—์„œ๋Š” ๋ฒ„ํŠผ๊ณผ button๋ณ€์ˆ˜๋งŒ Outlet ์—ฐ๊ฒฐ์„ ํ•ด์ค€๋‹ค.)

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button: UIButton!

    @objc func buttonAction(_ sender : Any){
      print(#function)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let actionSelector = #selector(buttonAction(_:))
        button.addTarget(self, action: actionSelector, for: .touchUpInside)   
    }
}

#selector๋Š” ์˜ค๋ธŒ์ ํŠธ-c ์—์„œ ์‚ฌ์šฉ๋˜๋˜๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ์„ ํƒํ•  ํ•จ์ˆ˜ ์•ž์— @objc๋ฅผ ๋ถ™์—ฌ์ค˜์•ผํ•œ๋‹ค.

Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.