gpt4 book ai didi

ios - 在 Swift 中重用 UIButton 的属性的最佳方法是什么

转载 作者:可可西里 更新时间:2023-10-31 23:58:55 28 4
gpt4 key购买 nike

当使用 inputAccessoryView 点击 UITextField 时,我有一堆按钮添加到 UIToolbar。除了标题之外,所有这些按钮都是相同的,我希望能够重用 UI 属性,例如 titleColorframe 等。

完成上述内容的最有效方法是什么?

这是代码...

    // code for first button
let button1 = UIButton();
button1.backgroundColor = UIColor.orangeColor()
button1.setTitle("button1", forState: .Normal)
button1.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button1.setTitleColor(UIColor.orangeColor(), forState: .Highlighted)
button1.frame = CGRect(x:0, y:0, width:35, height:35)
button1.addTarget(self, action: #selector(myFunction), forControlEvents: UIControlEvents.TouchUpInside)

// code for second button which is identical to the first button
let button2 = UIButton();
button2.backgroundColor = UIColor.orangeColor()
button2.setTitle("button2", forState: .Normal)
button2.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button2.setTitleColor(UIColor.orangeColor(), forState: .Highlighted)
button2.frame = CGRect(x:0, y:0, width:35, height:35)
button2.addTarget(self, action: #selector(myFunction), forControlEvents: UIControlEvents.TouchUpInside)

let barButton = UIBarButtonItem()
barButton.customView = button

let barButton2 = UIBarButtonItem()
barButton2.customView = button2

let toolBar = UIToolbar()
toolBar.items = [ barButton, barButton2]
toolBar.sizeToFit()

myTextField.inputAccessoryView = toolBar

最佳答案

将重复代码重构为单个本地函数。

func configure(_ button:UIButton) {
button.backgroundColor = UIColor.orangeColor()
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button.setTitleColor(UIColor.orangeColor(), forState: .Highlighted)
button.frame = CGRect(x:0, y:0, width:35, height:35)
button.addTarget(self, action: #selector(myFunction), forControlEvents: UIControlEvents.TouchUpInside)
}

// code for first button
let button1 = UIButton()
button1.setTitle("button1", forState: .Normal)
configure(button1)

// code for second button which is identical to the first button
let button2 = UIButton()
button2.setTitle("button2", forState: .Normal)
configure(button2)

关于ios - 在 Swift 中重用 UIButton 的属性的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442307/

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