2

For example If I have multiple IBOutlet like this:

@IBOutlet weak var x1: UITextField!
@IBOutlet weak var x2: UITextField!
@IBOutlet weak var x3: UITextField!
@IBOutlet weak var x4: UITextField!
@IBOutlet weak var x5: UITextField!
@IBOutlet weak var x6: UITextField!
@IBOutlet weak var x7: UITextField!
@IBOutlet weak var x8: UITextField!
@IBOutlet weak var x9: UITextField!
@IBOutlet weak var x10: UITextField!
@IBOutlet weak var x11: UITextField!
@IBOutlet weak var x12: UITextField!

How to change for example the border for all the IBOutlet :

self.x1.layer.borderWidth = 0.5
self.x1.layer.borderColor = UIColor.lightGrayColor().CGColor
self.x1.layer.cornerRadius = 5;

without writing a lot of code?

2 Answers2

1

You can define a collection of IBOutlets in Swift, like this:

@IBOutlet var collectionOfTextFields: Array<UITextField>?

Use IB to add all the desired fields to collectionOfTextFields. Now you can use a simple loop to set attributes of all your text fields without writing a lot of code.

You should be able to go even further, and eliminate all your x1..x12 variables from the code by setting tag attribute of your UITextFields in IB, and them using these tags in your processing code to differentiate among the twelve fields in your interface.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • How to find an IBOutlet from the array? –  Nov 24 '15 at 20:56
  • 1
    @Sarita Iterate and look for the tag that you gave it in the interface builder. [Here is an answer](http://stackoverflow.com/a/24066595/335858) that shows how to enumerate a collection of UI elements. – Sergey Kalinichenko Nov 24 '15 at 21:10
0

Add them to an array and loop through it.

for var x: UITextField in array {
  x.layer.borderWidth = 0.5
  ...
}
Max
  • 1,143
  • 7
  • 7