Swift에서 UIColorFromRGB를 어떻게 사용할 수 있습니까?
Objective-C에서는이 코드를 사용하여 뷰에 대한 RGB 색상 코드를 설정합니다.
#define UIColorFromRGB(rgbValue)
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
view.backgroundColor=UIColorFromRGB(0x209624);
Swift에서 어떻게 사용할 수 있습니까?
다음은 해당 함수의 Swift 버전입니다 ( UInt
값 의 UIColor 표현을 가져 오기 위해 ) :
func UIColorFromRGB(rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
view.backgroundColor = UIColorFromRGB(0x209624)
나는 넣고 싶었다
cell.backgroundColor = UIColor.colorWithRed(125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0)
그러나 그것은 작동하지 않았습니다.
그래서 사용했습니다 :
For Swift
cell.backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)
그래서 이것이 제가 찾은 해결 방법입니다.
나는 Nate Cook의 대답을 정말 좋아했지만 조금 더 관용적 인 것을 원했습니다. 나는 이것이 사용자 정의 확장을 통한 편의 초기화를위한 정말 좋은 사용 사례라고 생각합니다.
// UIColorExtensions.swift
import Foundation
import UIKit
extension UIColor {
convenience init(rgb: UInt) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
이제 다음과 같이 사용할 수 있습니다.
view.backgroundColor = UIColor(rgb: 0x209624)
라이브러리가 아닌 클라이언트 코드에서 이와 같은 UIKit 클래스를 원숭이 패치하는 것이 좋습니다.
myLabel.backgroundColor = UIColor(red: 50.0/255, green: 150.0/255, blue: 65.0/255, alpha: 1.0)
프로그래밍 방식으로 색상을 추가하는 가장 간단한 방법은 ColorLiteral 을 사용하는 것 입니다.
예제와 같이 ColorLiteral 속성을 추가하면 Xcode에서 선택할 수있는 전체 색상 목록을 표시합니다. 이렇게하면 코드가 적고 HEX 값 또는 RGB를 추가 할 수 있다는 장점이 있습니다 . 또한 스토리 보드에서 최근에 사용한 색상을 얻을 수 있습니다.
예 : self.view.backgroundColor = ColorLiteral
16 진수가 아닌 문자열에서 시작하는 경우 16 진수 문자열을 가져와 UIColor를 반환하는 함수입니다.
(형식 : #ffffff
또는 으로 16 진수 문자열을 입력 할 수 있습니다. ffffff
)
용법:
var color1 = hexStringToUIColor("#d3d3d3")
스위프트 4 :
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
스위프트 3 :
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
스위프트 2 :
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString
if (cString.hasPrefix("#")) {
cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
}
if ((cString.characters.count) != 6) {
return UIColor.grayColor()
}
var rgbValue:UInt32 = 0
NSScanner(string: cString).scanHexInt(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
출처 : arshad / gist : de147c42d7b3063ef7bc
들어 엑스 코드 9 사용하는 UIColor
RGB 값과.
shareBtn.backgroundColor = UIColor( red: CGFloat(92/255.0), green: CGFloat(203/255.0), blue: CGFloat(207/255.0), alpha: CGFloat(1.0) )
시사:
UIColor에 대한 추가 Apple 문서를 참조하십시오 .
I have used the following in swift.
let appRedColor = UIColor(red: 200.0/255.0, green: 16.0/255.0, blue: 46.0/255.0, alpha: 1.0)
let appSilverColor = UIColor(red: 236.0/255.0, green: 236.0/255.0, blue: 236.0/255.0, alpha: 1.0)
let appWhiteColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
let appNavyColor = UIColor(red: 19.0/255.0, green: 41.0/255.0, blue: 75.0/255.0, alpha: 1.0)
solution for argb format:
// UIColorExtensions.swift
import UIKit
extension UIColor {
convenience init(argb: UInt) {
self.init(
red: CGFloat((argb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((argb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(argb & 0x0000FF) / 255.0,
alpha: CGFloat((argb & 0xFF000000) >> 24) / 255.0
)
}
}
usage:
var clearColor: UIColor = UIColor.init(argb: 0x00000000)
var redColor: UIColor = UIColor.init(argb: 0xFFFF0000)
UIColorFromRGB in Swift 4
button.layer.backgroundColor = UIColor(red: 112.0/255, green: 86.0/255, blue: 164.0/255, alpha: 1.0).cgColor
This is worked for me in swift. Try this
bottomBorder.borderColor = UIColor (red: 255.0/255.0, green: 215.0/255.0, blue: 60/255.0, alpha: 1.0).CGColor
adding a swift 3 option:
cell.layer.borderColor = UIColor (red: 192.0/255.0, green: 192.0/255.0, blue: 197/255.0, alpha: 1.0).cgColor
You cannot use a complex macros like #define UIColorFromRGB(rgbValue)
in swift. The replacement of simple macro in swift is global constants like
let FADE_ANIMATION_DURATION = 0.35
Still the complex macros that accept parameters are not supported by swift. you could use functions instead
Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.
Excerpt from Using swift with cocoa and objective C
Check @Nate Cooks answer for the Swift version of that function to be used here
You can use this:
//The color RGB #85CC4B
let newColor = UIColor(red: CGFloat(0x85)/255
,green: CGFloat(0xCC)/255
,blue: CGFloat(0x4B)/255
,alpha: 1.0)
Nate Cook's answer is absolutely correct. Just for greater flexibility, I keep the following functions in my pack:
func getUIColorFromRGBThreeIntegers(red: Int, green: Int, blue: Int) -> UIColor {
return UIColor(red: CGFloat(Float(red) / 255.0),
green: CGFloat(Float(green) / 255.0),
blue: CGFloat(Float(blue) / 255.0),
alpha: CGFloat(1.0))
}
func getUIColorFromRGBHexValue(value: Int) -> UIColor {
return getUIColorFromRGBThreeIntegers(red: (value & 0xFF0000) >> 16,
green: (value & 0x00FF00) >> 8,
blue: value & 0x0000FF)
}
func getUIColorFromRGBString(value: String) -> UIColor {
let str = value.lowercased().replacingOccurrences(of: "#", with: "").
replacingOccurrences(of: "0x", with: "");
return getUIColorFromRGBHexValue(value: Int(str, radix: 16)!);
}
And this is how I use them:
// All three of them are identical:
let myColor1 = getUIColorFromRGBHexValue(value: 0xd5a637)
let myColor2 = getUIColorFromRGBString(value: "#D5A637")
let myColor3 = getUIColorFromRGBThreeIntegers(red: 213, green: 166, blue: 55)
Hope this will help. Everything is tested with Swift 3/Xcode 8.
This is a nice extension for UIColor. You can use enum values(hex, string) and direct string values when you creating UIColor objects.
The extension we deserve https://github.com/ioramashvili/UsefulExtensions/blob/master/Extensions.playground/Pages/UIColor.xcplaygroundpage/Contents.swift
I can see its already been answered but still hope one liner will help in better way.
import UIKit
let requiredColor = UIColor(red: CGFloat((rgbValue & 0xFF0000) >> 16)/255,
green: CGFloat((rgbValue & 0x00FF00) >> 8)/255,
blue: CGFloat(rgbValue & 0x0000FF)/255, alpha :1)
Updated: :Changes done as per example explained by Author of question to provide hex values
Swift3에서 이미 선택한 색상으로 시작하는 경우 RGB 값을 온라인 ( http://imagecolorpicker.com ) 으로 가져와 UIColor로 정의 된 값을 사용할 수 있습니다. 이 솔루션은이를 배경으로 구현합니다.
@IBAction func blueBackground(_ sender: Any) {
let blueColor = UIColor(red: CGFloat(160/255), green: CGFloat(183.0/255), blue: CGFloat(227.0/255), alpha: 1)
view.backgroundColor = blueColor
@Vadym은 위의 주석에서 언급했으며 단일 소수점으로 CGFloat를 정의하는 것이 중요합니다.
이 초기화를 사용하여 간단히 수행 할 수 있습니다.
view.backgroundColor = UIColor(hex: "067AB5")
참고 URL : https://stackoverflow.com/questions/24074257/how-can-i-use-uicolorfromrgb-in-swift
'program story' 카테고리의 다른 글
현재 날짜에서 7 일 빼기 (0) | 2020.08.10 |
---|---|
vi 다시 그리기 화면을 만드는 방법은 무엇입니까? (0) | 2020.08.10 |
Scalaz 7 zipWithIndex / group 열거로 메모리 누수 방지 (0) | 2020.08.10 |
나침반을 포함한 Android 휴대 전화 방향 개요 (0) | 2020.08.10 |
XPath의 인덱스가 0이 아닌 1로 시작하는 이유는 무엇입니까? (0) | 2020.08.10 |