ios - 是否可以在 Swift 中连接变量名和字符串/整数?

标签 ios swift uicolor

在 Javascript 或 jQuery 中,可以像这样连接字符串和变量名:

var id = 5;
$("#wrapper_" + id).hide();

我想用 Swift 达到同样的效果,比如:

func eventColors (colorID: Int, view: UIView) {
    view.backgroundColor = Constants.Color.eventColor + colorID // Incorrect
}

常量结构:

struct Constants {

   struct Color {
      static let eventColor1: UIColor = UIColor(red:0.06, green:0.44, blue:0.64, alpha:1)
      static let eventColor2: UIColor = UIColor(red:0.86, green:0.30, blue:0.99, alpha:1)
      static let eventColor3: UIColor = UIColor(red:0.50, green:0.44, blue:0.64, alpha:1)
   }

}

最佳答案

您不能在 Swift 中即时创建变量名。您应该考虑在此处使用数组。使 eventColor 成为颜色数组:

struct Constants {

    struct Color {
        static let eventColor: [UIColor] = [
            UIColor(red:0.06, green:0.44, blue:0.64, alpha:1),
            UIColor(red:0.86, green:0.30, blue:0.99, alpha:1),
            UIColor(red:0.50, green:0.44, blue:0.64, alpha:1)
        ]
    }

}

然后像这样选择你的颜色:

view.backgroundColor = Constants.Color.eventColor[colorID - 1]

关于ios - 是否可以在 Swift 中连接变量名和字符串/整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49816899/

相关文章:

ios - 如何在 UIImage 中使一种颜色透明

java - 如何给JButton设置 "very dark blue "背景色?

swift - RealityKit – 如何编辑或添加光照?

IOS:从 JSON 中检测 NSNull 不起作用

ios - 无法将 Lottie 动画 View 添加到 Collection View 单元格

ios - 一旦触摸以编程方式创建的 View (窗口),就调用操作

ios - CTCarrier 在所有属性上返回 nil

ios - 避免在 Swift 中将重复的图像上传文件上传到 Parse.com

ios - UITabbar项目objective-c中的颜色图标

ios - 切换子viewController使用分段控制