해당 포스트는 안드로이드 개발자가 iOS개발을 처음도전하면서 잘 정리되어 있지 않던 내용들을 정리해놓은 글 입니다.
버튼을 만들고 버튼을 터치했을때 이벤트를 발생시키기 위해서는 크게 가지로 구현할 수 있습니다. (해당 포스트에서는 스토리보드를 사용하지 않습니다.)
1. View에서 버튼 생성
2. 버튼을 눌렀을 때, 실행할 함수 정의
3. addTarget을 통해 버튼 이벤트 연결
1. View에서 버튼 생성
ViewController와 MainView를 생성하여 화면에 버튼 하나를 생성합니다.
// ViewController.swift
import UIKit
class ViewController: UIViewController {
lazy var mainView: MainView = {
return MainView(frame: self.view.bounds)
}()
static func instance() -> ViewController {
return ViewController(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view = mainView
view.backgroundColor = .white
}
}
// MainView.swift
import UIKit
class MainView: UIView {
lazy var button: UIButton = {
let button = UIButton()
button.setTitle("Button", for: .normal)
button.setTitleColor(.black, for: .normal)
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(button)
button.frame = CGRect(x: 200, y: 200, width: 100, height: 100)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
2.버튼을 눌렀을 때, 3.실행될 함수 정의와 연결
버튼이 눌렸을 때 함수인 func onTapButton()를 정의합니다.
(@objc를 붙여줘야 함수를 인식합니다.
또한 addTarget함수를 통해 버튼이 눌렸을 때 onTapButton()함수를 호출시키도록 정의합니다.
// ViewController.swift
import UIKit
class ViewController: UIViewController {
lazy var mainView: MainView = {
return MainView(frame: self.view.bounds)
}()
static func instance() -> ViewController {
return ViewController(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view = mainView
view.backgroundColor = .white
mainView.button.addTarget(self, action: #selector(onTapButton), for: .touchUpInside)
}
@objc
func onTapButton() {
print("Button was tapped.")
}
}
결과 화면
'iOS' 카테고리의 다른 글
[iOS/Swift] 스토리보드 없이 UIScrollView 만들기 (using Snapkit) (2) | 2020.02.04 |
---|---|
[iOS13] 스토리보드 없이 프로젝트 시작하기 (0) | 2020.01.26 |
아이폰 다양한 해상도 비율에 맞게 AutoLayout 그리기(with SnapKit) (0) | 2020.01.14 |
[RxSwift, RxCocoa] bind와 subscirbe의 차이점 (0) | 2020.01.07 |
[iOS] 커스텀 폰트 적용하기 (Swift) (0) | 2019.07.14 |