Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make UITextField appear with Swift Code

Tags:

ios

swift

I want to make the following UITextField appear when I compile and run the application. I have the UITextField declared and initialised as:

var myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200.00, height: 40.00));

However when I run the app, this text field does not appear. What Swift code would make the textfield appear?

like image 531
Stephen Fox Avatar asked Mar 27 '26 14:03

Stephen Fox


1 Answers

You have to actually add the text field to the view hierarchy, which is done slightly differently depending on the class that you're in. If for example, you're in a UIViewController subclass, you add it as a subview of the UIView attached to the view controller's view property.

var myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200.00, height: 40.00));
self.view.addSubview(myTextField)

Or, if you're working with a subclass of UIView, you could use:

self.addSubview(myTextField)

After you've added your text field to the view hierarchy, it's still possible that you won't be able to see it. By default, text field will have a white background color, no text, and no border around it. This can all be changed through use of the following properties.

myTextField.backgroundColor = UIColor.redColor()
myTextField.text = "some string" 
myTextField.borderStyle = UITextBorderStyle.Line
like image 158
Mick MacCallum Avatar answered Mar 29 '26 06:03

Mick MacCallum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!