swift使UIButtons输入文本到文本框中

时间:2016-09-01 22:15:25

标签: ios swift xcode7

我想知道是否可以在按下时将UIButton输入文本输入文本框

override func viewDidLoad() {
super.viewDidLoad()

var textBox = UITextField(frame: CGRectMake(x, y, w, h))
    textBox.borderStyle = UITextBorderStyle.Line
    self.view.addSubview(textBox)

var button = UIButton(frame: CGRectMake(x, y, w, h))
    button.backgroundColor = UIColor.blueColor()
    self.view.addSubview(button)
}

有没有办法让var按钮输入文本到文本框(var textBox)

1 个答案:

答案 0 :(得分:0)

使用addTarget

添加到按钮的选择器方法
var textBox = UITextField!
var button = UIButton!
override func viewDidLoad() {
    super.viewDidLoad()
    textBox = UITextField(frame: CGRectMake(x, y, w, h))
    textBox.borderStyle = UITextBorderStyle.Line
    self.view.addSubview(textBox)
    button = UIButton(frame: CGRectMake(x, y, w, h))
    button.backgroundColor = UIColor.blueColor()
    button.addTarget(self, 
        action:#selector(buttonTapped),
        forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(button)
}

func buttonTapped(object:AnyObject) {
    textBox?.text = "your text"
}