📱 iOS/UIKit

[UIKit] UIButton 타입과 메소드

kyxxn 2024. 8. 21. 12:47

학습 목표

  • 당연하게 써온 UIButton들 내부 프로퍼티, 메소드 톺아보기

학습 내용

UIButton 타입

아래 실습에서 사용될 코드

let myButton = UIButton(type: ??).then {
    $0.backgroundColor = .systemOrange
    $0.layer.cornerRadius = 12
}

기본 타입

  • system (.system):
    • 기본적인 시스템 스타일의 버튼
    • iOS 디자인 가이드라인에 맞는 기본 버튼
    • 텍스트와 터치 피드백(애니메이션 효과)을 제공

커스텀

  • custom (.custom):
    • 기본적인 스타일이 적용되지 않음
    • 버튼의 배경 이미지, 텍스트, 색상 등을 모두 커스터마이징 가능

i 인포 나타내기

  • detailDisclosure (.detailDisclosure):

    • 작은 원형 “i” 아이콘과 함께 나타나는 버튼
    • 주로 세부 정보 화면으로 이동하는 링크로 사용됨
  • infoLight (.infoLight):

    • 밝은 색상의 “i” 아이콘 버튼, 주로 어두운 배경에서 사용
  • infoDark (.infoDark):

    • 어두운 색상의 “i” 아이콘 버튼, 주로 밝은 배경에서 사용됩니다.

+ 추가 버튼

  • contactAdd (.contactAdd):
    • 플러스 기호(+)가 포함된 버튼
    • 연락처 추가와 같은 작업에 사용됨

x 닫는 버튼

  • close (.close):
    • 닫기 버튼으로, 작은 X 모양의 아이콘
    • 팝업 창을 닫는 작업에 자주 사용됨

setTitle(_:for:) 파라미터

아래 실습에서 사용될 코드

let myButton = UIButton(type: .system).then {
    $0.setTitle("완료", for: .normal)
    $0.setTitleColor(.white, for: .normal)

    $0.setTitle("비활성", for: .disabled)
    $0.setTitleColor(.darkGray, for: .disabled)

    $0.setTitle("선택", for: .selected)
    $0.setTitleColor(.green, for: .selected)

    $0.backgroundColor = .systemOrange
    $0.layer.cornerRadius = 12
    $0.isEnabled = false
}

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .systemBackground

    setCalendarView()
    setButton()
    setSelectionBehavior()
}

override func viewDidAppear(_ animated: Bool) {
    sleep(3)
    myButton.isEnabled = true
}
  • normal (.normal):
    • 버튼이 아무 상태도 아닌 기본 상태일 때 표시되는 텍스트
  • highlighted (.highlighted):
    • 버튼이 터치되었을 때(터치다운) 표시되는 텍스트
    • 이 상태에서는 텍스트 색상이 변경되거나, 버튼이 약간 어두워지는 효과가 적용
  • disabled (.disabled):
    • 버튼이 비활성화되었을 때 표시되는 텍스
  • selected (.selected):
    • 버튼이 선택된 상태에서 표시되는 텍스트
    • 이 상태는 토글 버튼처럼 선택/해제 가능한 버튼에서 자주 사용

Button의 프로퍼티 중 is 로 시작하는 Bool 타입들

UIView - UIControl - UIButton 구조로 이루어져 있음
UIButton에만 있는 건

/// If pointer effects are enabled for the button, this will return true when an effect is active.
@available(iOS 15.0, *)
open var isHovered: Bool { get }
/// Returns true while the button is presenting a menu.
@available(iOS 15.0, *)
open var isHeld: Bool { get }

open var isSelected: Bool // default is NO may be used by some subclasses or by application
open var isHighlighted: Bool // default is NO. this gets set/cleared automatically when touch enters/exits during tracking and cleared on up
open var isTracking: Bool { get }
open var isTouchInside: Bool { get } // valid during tracking only

isHovered

  • UIButton의 프로퍼티, iOS 15 이상
  • 버튼 위에 마우스 올라간 경우 (근데 모바일에선..?, 시뮬레이터, 실기기에서도 잘 안됨)

isHeld

  • UIButton의 프로퍼티, iOS 15 이상

  • 버튼이 메뉴 표시중일 때 true 반환

  • UIButton이 UIContextMenuInteraction 또는 UIMenu와 연결되어 있고,
    해당 메뉴가 활성화된 동안 이 속성이 true

  • 예시코드

      let myButton = UIButton(type: .system).then {
          $0.setTitle("완료", for: .normal)
          $0.setTitleColor(.white, for: .normal)
    
          $0.backgroundColor = .systemOrange
          $0.layer.cornerRadius = 12
          $0.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
      }
    
      @objc func buttonTapped() {
          if myButton.isHeld {
              print("버튼이 현재 메뉴를 표시하고 있습니다.")
          } else {
              // 메뉴를 표시하도록 설정
              let menu = UIMenu(title: "옵션", children: [
                  UIAction(title: "옵션 1", handler: { _ in print("옵션 1 선택") }),
                  UIAction(title: "옵션 2", handler: { _ in print("옵션 2 선택") })
              ])
              myButton.menu = menu
              myButton.showsMenuAsPrimaryAction = true
          }
      }

isUserInteractionEnabled

  • UIView의 프로퍼티
  • 버튼이 사용자 상호작용을 허용하게 할 건지,
    만약 False이면 모든 상호작용(터치 이벤트) 불가능

isOpaque

  • UIView의 프로퍼티
  • 버튼 불투명 여부를 물음 (얘도 시뮬에서 못 써봄)

참조 링크

https://developer.apple.com/documentation/uikit/uibutton

https://developer.apple.com/documentation/uikit/uicontrol

https://developer.apple.com/documentation/uikit/uiview