[Swift] 스위프트 랜덤(random) 난수 색상 값 만들기
- 언어 / 스위프트
- 2022. 9. 30.
반응형
randomColor
스위프트를 이용해 아이폰 개발을 하다보면 간혹 UIColor를 랜덤으로 사용해야할 경우가 있습니다. 다음과 같은 익스텐션을 만들고 쉽게 사용이 가능합니다. 원리는 간단합니다. CGFloat의 random함수를 이용해 0부터 1 사이의 값을 새로운 UIColor 객체를 만들 때 사용합니다.

우선 새로운 UIColor 익스텐션(extension)을 만듭니다. 그리고 randomColor 라는 함수를 만듭니다. randomAlpha 라는 Boolean 값이 있는데 이는 난수를 발생시킬때 Alpha 값에 대해서도 포함 할지를 나타냅니다. 기본값은 false 입니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIColor { | |
class func randomColor(randomAlpha: Bool = false) -> UIColor { | |
let redValue = CGFloat.random(in: 0...1) | |
let greenValue = CGFloat.random(in: 0...1) | |
let blueValue = CGFloat.random(in: 0...1) | |
let alphaValue = randomAlpha ? CGFloat.random(in: 0...1) : 1 | |
return UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: alphaValue) | |
} | |
} |
다음과 같이 사용할 수 있습니다.
vc.view.backgroundColor = UIColor.randomColor()
// Alpha 값 포함
vc.view.backgroundColor = UIColor.randomColor(randomAlpha: true)
반응형
'언어 > 스위프트' 카테고리의 다른 글
[Swift] iOS 저전력(절전) 모드 확인하기 (2) | 2023.03.14 |
---|---|
[Swift] Date 객체에 1일(하루)을 추가해서 Date 객체 변환하기 (0) | 2023.03.11 |
[Swift] AVAudioPlayer iOS 오디오 wav 파일 재생하기 (0) | 2023.02.16 |
[Swift] userContentController JSON 데이터 파싱하기 (0) | 2023.02.11 |
[Swift] 스위프트 toString 구현하기 (0) | 2022.09.27 |