[swift] SnapKit으로 뷰의 액션 시트 설정하기

개요

SnapKit은 Swift에서 사용하기 편리한 레이아웃 라이브러리입니다. 이 라이브러리를 사용하여 뷰의 액션 시트를 설정하는 방법을 알아보겠습니다.

필요한 패키지 설치하기

먼저, SnapKit을 사용하기 위해 프로젝트에 해당 패키지를 설치해야 합니다. Podfile에 다음과 같이 추가합니다.

pod 'SnapKit'

그리고 터미널에서 pod install 명령을 실행하여 패키지를 설치합니다.

액션 시트 설정하기

뷰에 액션 시트를 설정하기 위해 다음 단계를 따릅니다.

  1. 액션 시트를 표시할 버튼을 생성합니다.
let button = UIButton()
button.setTitle("Show Action Sheet", for: .normal)
button.setTitleColor(.systemBlue, for: .normal)
self.view.addSubview(button)

button.snp.makeConstraints { (make) in
    make.center.equalToSuperview()
}
  1. 버튼의 액션 메소드를 생성하여 액션 시트를 표시합니다.
@objc func showActionSheet() {
    let alertController = UIAlertController(title: nil, message: "Choose an option", preferredStyle: .actionSheet)
    
    let option1 = UIAlertAction(title: "Option 1", style: .default) { (action) in
        // Option 1 선택 시 실행할 동작
    }
    
    let option2 = UIAlertAction(title: "Option 2", style: .default) { (action) in
        // Option 2 선택 시 실행할 동작
    }
    
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    
    alertController.addAction(option1)
    alertController.addAction(option2)
    alertController.addAction(cancelAction)
    
    self.present(alertController, animated: true, completion: nil)
}

button.addTarget(self, action: #selector(showActionSheet), for: .touchUpInside)

결과 확인하기

위의 코드를 실행하여 액션 시트를 표시하는 버튼을 생성하고, 버튼을 눌렀을 때 액션 시트가 나타나는지 확인할 수 있습니다.

이제 SnapKit을 사용하여 뷰의 액션 시트를 설정하는 방법에 대해 알아보았습니다.

참고 자료