gpt4 book ai didi

ios - 按下按钮时更改自定义 UIButton (CoreGraphics) 的背景颜色

转载 作者:行者123 更新时间:2023-11-30 13:20:24 27 4
gpt4 key购买 nike

有人知道如何更改自定义 UIButton 的背景颜色吗?

enter image description here

正如您在图像中看到的,名为“plot”的按钮的背景色为橙色。但左边的按钮(黑色三角形)不是橙色的。

我想要的是,当我按下“绘图”或“奖励”按钮时,它旁边的三角形按钮也会随之改变。

这是我的代码:

@IBDesignable class LeadingButton: UIButton {

override func drawRect(rect: CGRect) {

// *Draw triangle button:

// Create context for triangle
let context = UIGraphicsGetCurrentContext()

// *Put information into context:

// Info for drawing triangle:
CGContextMoveToPoint(context, 17, 0)
CGContextAddLineToPoint(context, 0, 40)
CGContextAddLineToPoint(context, 17, 40)
CGContextAddLineToPoint(context, 17, 0)

// Info color triangle
CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)

// Color in triangle with specified color
CGContextFillPath(context)

// Draw triangle
CGContextStrokePath(context)
}
}

class MovieDetailController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// For changing background color of buttons
self.buttonArray = [plotB, directorB, writerB, actorsB, countryB, awardB, posterB, leadingB, trailingB]

}

func isButton(pressed: Int) {

switch pressed {
case 0...8:

let selectedButton = buttonArray[pressed]
selectedButton.backgroundColor = UIColor.orangeColor()

var idDictionary = [0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6]
idDictionary.removeValueForKey(pressed)

for (_, value) in idDictionary {

if value == 6 {

}
else {

let remainButtons = buttonArray[value]
remainButtons.backgroundColor = UIColor.blackColor()
}
}

default:
print("test")
}

}

最佳答案

将绘图代码移至绘图函数中,如下所示:

func drawTriangle() {
//Move draw rect code into here
}

并从drawRect调用此函数。还要确保在drawRect中调用super

override func drawRect(rect: CGRect) {
super.drawRect(rect)
drawTriangle()
}

然后您可以在按钮上添加一个变量来指示其颜色,并且在 did 集中您可以设置三角形颜色

var triangleColor:UIColor = UIColor.blackColor() {
didSet {
drawTriangle()
}
}

然后在绘制三角形时取颜色即可:

替换:

CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)

与:

CGContextSetFillColorWithColor(context, triangleColor.CGColor)

然后您应该能够检查您按下的按钮是否为“绘图/奖励”并使用以下方法设置相应的按钮颜色:

(triangleButtonVariable).triangleColor = YourColour

关于ios - 按下按钮时更改自定义 UIButton (CoreGraphics) 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37823864/

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