【问题标题】:Round button on custom class with UIAppearance带有 UIAppearance 的自定义类上的圆形按钮
【发布时间】:2018-06-17 13:17:02
【问题描述】:

我正在尝试使用 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 上测试。

【问题讨论】:

    标签: ios swift uibutton uiappearance


    【解决方案1】:

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

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

    按钮的类型定义了它的基本外观和行为。您可以在创建时使用 init(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
    }
    

    【讨论】:

    • 首先,非常感谢您提供广泛而清晰的答案。我试过你的方法,它确实有效。这只是因为我试图在我的代码中坚持一种风格指南的来源,实际上直到现在还没有缺少 UIAppearance() 的任何功能。好像你不能在一个地方做所有事情:(
    猜你喜欢
    • 1970-01-01
    • 2020-03-24
    • 2018-12-30
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2020-07-10
    相关资源
    最近更新 更多