UIKit

[UIKit] UIButton

usia_ 2024. 7. 29. 14:05
 

[UIKit] hierarchy, 계층구조

UIKit은 'User Interface Kit'으로 사용자 인터페이스를 구성하는데 사용하는 인터페이스이다.NSObject는 대부분의 Objective-C 클래스의 루트클래스이자, Swift에서도 기반 클래스가 되며, 기본적인 객체의

usiacode.tistory.com

[NSObject - UIResponder - UIView - UIControl - UIButton]

 

 

UIButton 은 사용자의 상호작용을 위해 사용되는 기본적인 객체로, 버튼을 눌렀을 때 특정 작업을 수행할 수 있도록 설정할 수 있다.

 

Property, Method
button.setTitle("Press Me", for: .normal) // 버튼 텍스트
button.setTitleColor(.white, for: .normal) // 버튼 텍스트 색깔
button.backgroundColor = .systemBlue // 배경색
button.layer.cornerRadius = 5 // 코너 둥글게
button.layer.borderWidth = 1 // 테두리 굵기
button.layer.borderColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1) // 테두리 색깔
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) // 버튼 텍스트 크기, 굵기
button.addTarget(self, action: #selector(myButtonTapped), for: .touchUpInside) 
// 버튼이 클릭됐을 때 실행되는 함수 myButtonTapped()

 

 

 

스토리보드에서 추가

'Command + Shift + L'

 

IBOutlet 과 IBAction으로 연결

 

 

코드로 추가
    private lazy var myButton: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .systemBlue
        button.layer.cornerRadius = 5
//        button.layer.borderWidth = 1
        //        button.layer.borderColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        button.setTitle("BMI 계산하기", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        button.addTarget(self, action: #selector(myButtonTapped), for: .touchUpInside)
        view.addSubview(button)
        return button
    }()
    
    // [AutoLayout]
    //func myButtonSetup() {
    //    myButton.translatesAutoresizingMaskIntoConstraints = false
    //
    //    NSLayoutConstraint.activate([
    //    myButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30),
    //    myButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30),
    //    myButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 30),
    //    myButton.heightAnchor.constraint(equalToConstant: 40)
    //    ])
    //}
    
    @objc func myButtonTapped() {
        <#버튼 눌렸을 때 실행되는 코드#>
    }

 

'UIKit' 카테고리의 다른 글

[UIKit] UITextField  (0) 2024.07.29
[UIKit] UISlider  (0) 2024.07.29
[UIKit] UILabel  (0) 2024.07.29
[UIKit] hierarchy, 계층구조  (0) 2024.07.29
[UIKit CodeSnippets] UITextField Snippet (Only-code)  (2) 2024.07.24