gpt4 book ai didi

ios - iOS 中的自定义 View 和自定义按钮

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

我创建了两个自定义类:CutomView 类(UIView 的子类)和 CustomButton 类(UIButton 的子类)。

class CustomView: UIView {

override func drawRect(rect: CGRect) {
// Drawing code
layer.masksToBounds = true
layer.borderWidth = 2.0
layer.borderColor = UIColor(colorLiteralRed: 0.0/255, green: 64.0/255, blue: 128.0/255, alpha: 1).CGColor
layer.cornerRadius = 10.0
let startColor = UIColor(colorLiteralRed: 255.0/255, green: 204.0/255, blue: 1.0, alpha: 1.0).CGColor
let endColor = UIColor(colorLiteralRed: 0, green: 128.0/255, blue: 1.0, alpha: 1.0).CGColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(origin: layer.frame.origin, size: layer.frame.size)
gradientLayer.colors = [startColor, endColor];
layer.addSublayer(gradientLayer)
}

@IBDesignable
class CustomButton: UIButton {
override func drawRect(rect: CGRect) {
// Drawing code
layer.masksToBounds = true
layer.borderWidth = 2.0
layer.borderColor = UIColor(colorLiteralRed: 0.0/255, green: 64.0/255, blue: 128.0/255, alpha: 1).CGColor
layer.cornerRadius = 2.0
let startColor = UIColor(colorLiteralRed: 192.0/255, green: 192.0/255, blue: 192.0/255, alpha: 1.0).CGColor
let endColor = UIColor(colorLiteralRed: 239.0/255, green: 239.0/255, blue: 239.0/255, alpha: 1.0).CGColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(origin: layer.frame.origin, size: layer.frame.size)
gradientLayer.colors = [startColor, endColor];
layer.addSublayer(gradientLayer)
}

}

我使用这些自定义子类来设计 View 和按钮。当我查看应用的自定义类时,它们工作正常,但由于某些原因,该按钮在模拟器或 iOS 设备中不可见。

如果有人能指出我的错误或帮助我修复它,那就太好了。

Storyboard and Preview shows the purple blue background and button

Simulator only displays purple blue background

最佳答案

您的layer.addSublayer调用将图层附加到您的图层层次结构中。因此,渐变是最后绘制的,有效地绘制在您的自定义按钮上。您希望渐变成为背景,因此请确保它是绘制的第一层。改变

layer.addSublayer(gradientLayer)

layer.insertSublayer(gradientLayer, atIndex: 0)

关于ios - iOS 中的自定义 View 和自定义按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36925742/

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