iOS 기본 (swift)
[iOS - swift] Roundable Button, cornerRadius 커스텀 버튼
jake-kim
2022. 5. 31. 01:23
Roundable 버튼
- layer.cornerRadius값이 width나 height의 값의 반일때 원이 되므로 이 특성을 사용
// ViewController.swift
NSLayoutConstraint.activate([
self.circleView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 120),
self.circleView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
self.circleView.widthAnchor.constraint(equalToConstant: 120),
self.circleView.heightAnchor.constraint(equalToConstant: 120)
])
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.circleView.layer.cornerRadius = 60 // width, height값의 반을 주면 원 모양
}
- cornerRadius 특성 테스트
- cornerRadius의 의미: 사각형 4곳의 corner의 반지름값을 설정하는데, 반지름 값을 짧은 변의 길이의 반으로 하면 Roundable 버튼이 완성
- cornerRadius가 직사각형 뷰에서 길이가 작은 쪽의 반값인 경우, 아래 2번째처럼 자연스러운 Roundable 버튼으로 형성
height 80, width 120 | cornerRadius = 40 | cornerRadius = 60 |
![]() |
![]() |
![]() |
- 위 특성을 이용하고 UIButton을 서브클래싱하여 Roundable 버튼을 정의
import UIKit
final class RoundableButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = min(self.frame.width, self.frame.height) / 2
}
}
(사용하는쪽)
private let roundableButton: RoundableButton = {
let button = RoundableButton()
button.backgroundColor = .gray
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()