我正在尝试以编程方式构建一个绘图应用程序,只是为了在 swift UIKIt 中获得乐趣,但现在我遇到了一个问题,我正在尝试创建一个颜色调色板来交换
UIColor
属性,为此我创建了一个枚举 Pencil
并使其CaseIterable
在函数中使用.allCases
迭代,以便我能够在UIButton
函数内以编程方式创建createColorButton
,但我看到的只是模拟器屏幕顶部的一个白色方块
这是我的职责
func createColorButton() -> [UIButton]{
var buttons: [UIButton] = []
for pencilCase in Pencil.allCases {
let button = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
button.backgroundColor = pencilCase.color
button.tag = pencilCase.hashValue
button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
buttons.append(button)
}
return buttons
}
这是我的
Pencil
枚举
enum Pencil: CaseIterable {
case black
case grey
case red
case darkblue
case lightBlue
case darkGreen
case lightGreen
case brown
case orange
case yellow
case eraser
init?(tag: Int) {
switch tag {
case 1:
self = .black
case 2:
self = .grey
case 3:
self = .red
case 4:
self = .darkblue
case 5:
self = .lightBlue
case 6:
self = .darkGreen
case 7:
self = .lightGreen
case 8:
self = .brown
case 9:
self = .orange
case 10:
self = .yellow
case 11:
self = .eraser
default:
return nil
}
}
// cases for penil.color
var color: UIColor {
switch self {
case .black:
return .black
case .grey:
return UIColor(white: 105/255.0, alpha: 1.0)
case .red:
return UIColor(red: 1, green: 0, blue: 0, alpha: 1.0)
case .darkblue:
return UIColor(red: 0, green: 0, blue: 1, alpha: 1.0)
case .lightBlue:
return UIColor(red: 51/255.0, green: 204/255.0, blue: 1, alpha: 1.0)
case .darkGreen:
return UIColor(red: 102/255.0, green: 204/255.0, blue: 0, alpha: 1.0)
case .lightGreen:
return UIColor(red: 102/255.0, green: 1, blue: 0, alpha: 1.0)
case .brown:
return UIColor(red: 160/255.0, green: 82/255.0, blue: 45/255.0, alpha: 1.0)
case .orange:
return UIColor(red: 1, green: 102/255.0, blue: 0, alpha: 1.0)
case .yellow:
return UIColor(red: 1, green: 1, blue: 0, alpha: 1.0)
case .eraser:
return .white
}
}
}
我正在将
createColorButton
函数传递到 secondViewController
UIViewController 中,但正如我提到的,它没有按我的预期工作。我只看到一个“白色方块”,而不是每个 Pencil.color
的 UI 按钮
override func viewDidLoad() {
super.viewDidLoad()
let buttons = createColorButton()
for button in buttons {
self.view.addSubview(button)
}
setupImageViews()
}
有什么建议可以让我让它发挥作用吗?
尝试将所有按钮插入垂直堆栈视图中。这将排列它们,使它们不在屏幕上的同一位置。