gpt4 book ai didi

ios - 带有 UIAppearance 的自定义类上的圆形按钮

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

我正在尝试使用 UIAppearance() 在自定义类上应用样式

class MainStyleButton: UIButton {}

带有代码:

let buttonView = MainStyleButton.appearance()
buttonView.backgroundColor = Style.buttonColor
buttonView.layer.cornerRadius = 5
buttonView.layer.borderWidth = 5
buttonView.layer.borderColor = Style.buttonColor.cgColor

它适用于颜色,但不幸的是不会使我的按钮变圆。我将不胜感激任何提示。在配备 iOS 11.2 的 iPhone X、8 模拟器上进行了测试。

最佳答案

我尝试复制您的方法并设置一个按钮。我尝试使用您的代码在 viewDidLoad 期间更改 UIViewController 中的按钮外观,并在 applicationDidFinishLaunching 期间更改 AppDelegate 中的按钮外观。我还测试了将按钮类型从默认类型 .system 更改为 .custom。这些似乎都不起作用,我无法覆盖您无法覆盖的相同属性。

来自Apple's docs据我了解,按钮类型定义了其外观以及可以覆盖哪些外观属性:

A button’s type defines its basic appearance and behavior. You specify the type of a button at creation time using the init(type:) method or in your storyboard file. After creating a button, you cannot change its type.

我不知道为什么您感兴趣的属性此时无法更改

<小时/>

但是,我想提供一种我个人使用的不同方法,允许您更改按钮的外观。由于您已经定义了自定义类,因此定义圆角半径和您想要的其他属性要简单得多,如下所示(或者您可以编写一个带有可以随时调用的参数的样式函数,以便能够更改外观基于按钮的使用位置):

class MainStyleButton: UIButton {
override func awakeFromNib() {
layer.borderColor = Style.buttonColor.cgColor
layer.borderWidth = 5
layer.cornerRadius = 5
}
}

或者您可以实例化/使用 IBOutlet 作为系统按钮并执行以下操作:

class MyViewController: UIViewController {
@IBOutlet weak var myButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// not necessary to do this is viewDidLoad, that's just my example
myButton.layer.borderColor = Style.buttonColor.cgColor
myButton.layer.cornerRadius = 5
myButton.layer.borderWidth = 5
}

关于ios - 带有 UIAppearance 的自定义类上的圆形按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50897040/

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