我有一个按钮,可以创建更多带有文本字段的按钮:
func CreateButtonWithIndex(index:Int) {
let newButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
newButton.setTitle(“Button”, forState: UIControlState.Normal)
newButton.addTarget(self, action: Selector("go:"), forControlEvents: UIControlEvents.TouchUpInside)
newButton.tag = index+1;
var textFieldButton: UITextField = UITextField()
textFieldButton.tag = index+1;
textFieldButton.text = “textfield”
self.view.addSubview(textFieldButton)
self.view.addSubview(newButton)
}
func go(sender: AnyObject) {
println(“ok press button“)
}
如何检测与按下的按钮对应的文本字段?
答案 0 :(得分:0)
将发件人转换为UIButton
@IBAction func go(sender: AnyObject) {
let yourButton = sender as UIButton
println(yourButton.titleLabel.text)
}
更好的是,如果您确定只有按钮才会调用" go
"行动,你可以这样做:
@IBAction func go(sender: UIButton) {
println(sender.titleLabel.text)
if(sender.titleLabel.text == "OK")
println("OK button was pressed")
}
更多信息可以在"比较字符串" Apple's Strings & Characters Swift documentation的部分和我找到的@IBOutlet in this tutorial。
答案 1 :(得分:0)
UIButton子类。将UITextField变量添加到子类UIButton。在创建UIButton子类后分配新的UITextField变量。
UIButton子类:
class TextFieldButton: UIButton {
var textField: UITextField! // use this to reference the related text field
}
您其他课程中的代码:
func CreateButtonWithIndex(index:Int) {
let newButton = UIButton.buttonWithType(UIButtonType.System) as TextFieldButton // use our new subclass
newButton.setTitle(“Button”, forState: UIControlState.Normal)
newButton.addTarget(self, action: Selector("go:"), forControlEvents: UIControlEvents.TouchUpInside)
newButton.tag = index+1;
var textFieldButton: UITextField = UITextField()
textFieldButton.tag = index+1;
textFieldButton.text = "textfield"
newButton.textField = textFieldButton // set reference to the text field
self.view.addSubview(textFieldButton)
self.view.addSubview(newButton)
}
func go(sender: AnyObject) {
println("ok press button")
println(sender.textField) // now we can access the related text field
}