Ice3343 Ice3343 - 3 months ago 14
Swift Question

swift Make UIButtons input text into a textbox

I was wondering if it is possible to make a UIButton input text into a text box when pressed

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)
}


Is there a way to make the var button input text to the text box (var textBox)

Answer

In your selector method added to your button using 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"
}
Comments