gpt4 book ai didi

ios - 在 iOS 中将字符串转换为十六进制?

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:09:49 25 4
gpt4 key购买 nike

我主要是让用户在 UITextField 中输入一个十六进制值,并将其写入一个字符串中,以将其用于颜色选择(教育目的)。如何将字符串转换为十六进制?

最佳答案

我不确定这是否是您在您的场景中想要的...看看这是否有用..

通过传递十六进制字符串调用第一个方法,作为返回,您将获得UIColor

- (UIColor *) colorWithHexString:(NSString *)hexString {
NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];
CGFloat alpha, red, blue, green;
alpha = 1.0f;
red = [self colorComponentFrom: colorString start: 0 length: 2];
green = [self colorComponentFrom: colorString start: 2 length: 2];
blue = [self colorComponentFrom: colorString start: 4 length: 2];
return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}

- (CGFloat) colorComponentFrom:(NSString *)string start:(NSUInteger)start length:(NSUInteger)length {
NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
unsigned hexComponent;
[[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
return hexComponent / 255.0;
}

关于ios - 在 iOS 中将字符串转换为十六进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17060318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com