fs_*_*gre 2 uibutton uitextfield uitoolbar ios swift
我有一堆按钮,UIToolbar
当我UITextField
点击使用时,我正在添加这些按钮inputAccessoryView
.所有这些按钮都是相同的标题以外的什么,我想能够做的就是重用UI属性,如titleColor
,frame
等.
什么是完成我上面描述的最有效的方法?
这是代码......
// 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
Run Code Online (Sandbox Code Playgroud)
将重复代码重构为单个本地函数.
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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
187 次 |
最近记录: |