gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:20:06 27 4
gpt4 key购买 nike

我在我的 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/

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