ios - 如何将自定义类设置为以编程方式创建的 UIButton?

标签 ios swift uibutton

我在 ViewController 中通过以下方式创建了一个按钮:

var userButton: Button!

override func viewDidLoad() {

    userButton = Button()
    userButton.frame = CGRect(x: self.view.frame.width / 2 + 90, y: 
    self.view.frame.height / 1.5 + 110, width: 100, height: 100)
    userButton.addTarget(self, action: #selector(MainController.userButtonTapped(sender:)), for: .touchUpInside)

    self.view.addSubview(userButton)
}

这是我创建的 Button 类:

import UIKit

@IBDesignable
class Button: UIButton {

// MARK: - PROPERTIES

@IBInspectable var cornerRadius: CGFloat = 3.0 {
    didSet {

        setupView()
    }
}

// MARK: - CONFIGURATION

override func awakeFromNib() {

    setupView()
}

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()

    setupView()
}

/**
 *  Sets default properties to the view.
 */
func setupView() {

    self.layer.cornerRadius = cornerRadius

    * Shadow properties */
    self.layer.shadowColor = SHADOW_COLOR.cgColor
    self.layer.shadowOpacity = 0.6
    self.layer.shadowRadius = 6.0
    self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
}
}

运行应用程序时,userButton 没有在类中设置的属性。但是,当我在 ViewController 中设置这些属性时,它就起作用了。为什么它不适用于类(class)?

最佳答案

改为编写此代码:-

override func awakeFromNib() {
    super.awakeFromNib()
    setupView()
}

在layoutSubviews()()中写入setUpView()

例如:-

 override func layoutSubviews()() {
        super.layoutSubviews()()
        setupView()
    }

关于ios - 如何将自定义类设置为以编程方式创建的 UIButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44340587/

相关文章:

iphone - 打印出[错误描述]中的错误信息

快速调用没有返回值的异步函数

swift - 如何在测试用例中测试CLLocationManager的不同权限

ios - Swift CGPoint x 和 y 覆盖编程约束

ios - UICollectionView 中的选择和取消选择问题

ios - 将集合转换为数组?

ios - swift 。使用 IBOutlet 更改多个 UIButton

ios - 通过 IF 语句在按钮上显示图像

ios - {FlashDevelop} 使用 AIR 和 FlashDevelop 构建 iOS

ios - 动画按钮图像时 UIButton 文本不可见