来自字符串数组的随机uicolor

时间:2016-01-25 01:05:52

标签: arrays swift background uicolor

我希望通过从预定的字符串数组(例如(红色,绿色,粉色))调用随机颜色来更改我的swift应用程序的背景颜色。

所以我有那个数组,我希望随机选择背景颜色作为其中一种颜色。

使用self.bg.background颜色导致xcode表示字符串无法转换为uicolor

2 个答案:

答案 0 :(得分:1)

以下是一种实现此目的的方法示例:

import UIKit

extension Array {
  func randomElement() -> Element {
    return self[Int(arc4random_uniform(UInt32(self.count)))]
  }
}

extension UIColor {
  enum ColorEnum: String {
    case red   // = "red"
    case green // = "green"
    case blue  // = "blue"
    case pink  // = "pink"

    func toColor() -> UIColor {
      switch self {
      case .red:
        return .redColor()
      case .green:
        return .greenColor()
      case .blue:
        return .blueColor()
      case .pink:
        return UIColor(hue: 1.0, saturation: 0.25, brightness: 1.0, alpha: 1.0)
      }
    }
  }

  static func fromString(name: String) -> UIColor? {
    return ColorEnum(rawValue: name)?.toColor()
  }
}

let colors = ["red", "green", "pink"] // stored as String
UIColor.fromString(colors.randomElement())

let enumColors: [UIColor.ColorEnum] = [.red, .green, .pink] // stored as enum
enumColors.randomElement().toColor()

答案 1 :(得分:0)

您无法直接转换任何字符串,例如" Green" "粉红"到UIColor对象。如果你只想使用这个,那么你必须创建与这些字符串匹配的自定义枚举到相应的UIColor对象。

意思是你可以使用我编写的UIColor扩展支持的下面表格中的字符串颜色。

  1. RGBA String(字符串必须用空格分隔" 0.5 0.6 0.7 1.0" 50%的红色60%的绿色70%的蓝色Alpha 100%)
  2. 例如十六进制字符串#ffffff(相当于白色)等于UIColor.white
  3. 要将这两个颜色字符串转换为UIColor,您可以使用以下UIColor扩展名

    extension UIColor {
    
    
    //Convert RGBA String to UIColor object
    //"rgbaString" must be separated by space "0.5 0.6 0.7 1.0" 50% of Red 60% of Green 70% of Blue Alpha 100%
    public convenience init?(rgbaString : String){
        self.init(ciColor: CIColor(string: rgbaString))
    }
    
    //Convert UIColor to RGBA String
    func toRGBAString()-> String {
    
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        return "\(r) \(g) \(b) \(a)"
    
    }
    //return UIColor from Hexadecimal Color string
    public convenience init?(hexString: String) {
    
            let r, g, b, a: CGFloat
    
            if hexString.hasPrefix("#") {
                let start = hexString.index(hexString.startIndex, offsetBy: 1)
                let hexColor = hexString.substring(from: start)
    
                if hexColor.characters.count == 8 {
                    let scanner = Scanner(string: hexColor)
                    var hexNumber: UInt64 = 0
    
                    if scanner.scanHexInt64(&hexNumber) {
                        r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                        g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                        b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                        a = CGFloat(hexNumber & 0x000000ff) / 255
                        self.init(red: r, green: g, blue: b, alpha: a)
                        return
                    }
                }
            }
    
            return nil
        }
    // Convert UIColor to Hexadecimal String
    func toHexString() -> String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        return String(
            format: "%02X%02X%02X",
            Int(r * 0xff),
            Int(g * 0xff),
            Int(b * 0xff)
        )
    }
    

    }

    要获取Array中存在的任何随机值,您可以在Array上创建扩展,如下所示。

    extension Array {
       func randomElement() -> Element {
            return self[Int(arc4random_uniform(UInt32(self.count)))]
       }
    }
    

    对于您的情况,您可以按如下方式创建UIColor数组

       //Define array to hold UIColor which will hold your Views background color  
        var arrOfColors = [UIColor]()
    
       //Create array of   RGBA String color like
        let arrRGBAStringColor = ["0.5 0.6 0.7 1.0","0.53 0.46 0.27 1.0","0.3 0.16 0.17 1.0"]
    
       //Create array of   Hexadecimal String color like
        let arrHexStringColor = ["#cccc41","#8e8e8e","#003300"]
    
    
        for stringColor in arrRGBAStringColor {
    
            //Use UIColor extension to convert RGBA string to UIColor
            if let color = UIColor(rgbaString : stringColor){
                arrOfColors.append(color)
            }
        }
        for stringColor in arrHexStringColor {
            //Use UIColor extension to convert Hexadecimal string to UIColor
            if let color = UIColor(hexString : stringColor){
                arrOfColors.append(color)
            }
        }
    
        //Now fetch any random color from your color array
        let randomColor = arrOfColors.randomElement()
    
        self.backgroundColor = randomColor