简体   繁体   中英

how to insert iboutlets into a array (swift3)

I am trying to group multiple iboutets into a array. This will make my coding workflow much faster if its possible to group. I have tried to code my idea but it does not work. What I am trying to do revolves around the let c = part. Code is below.

    import UIKit

class ViewController: UIViewController {
let c = {
@IBOutlet var a: UIButton!

@IBOutlet var b: UIButton!
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func turnOff(_ sender: Any) {
    c.isHidden = true

}}

Depending on your needs I see three options:

1. Outlet Collections

If you use interface builder, look for the Outlet Collection option when dragging out an outlet.

插座系列

Here is the syntax for manually creating outlet collections:

@IBOutlet var buttons: [UIButton]!

Now you can connect multiple buttons to the collection. The downside is that you no longer have simple access to individual buttons via this outlet.

2. Computed Property

If you would like to keep individual outlets for easy access I would probably create a computed property returning a collection:

@IBOutlet var a: UIButton!
@IBOutlet var b: UIButton!
var buttons: [UIButton] {
    return [a, b]
}

3. View Hierarchy

Depending on your layout needs you may be able to put all buttons into a common parent view. Now just hide/unhide the parent view.

Extending Collections for Option 1 and 2

The reason why you cannot use isHidden on the buttons collection is that Arrays don't have an isHidden property. You will have to iterate through the array (Tom Harrington pointed this out in the comments). If you have to do that a lot you can extend arrays of buttons by adding a method that forwards to the isHidden property of the array's elements. Here is an example for extending the more general type Sequence constrained to UIView elements (which includes arrays of buttons):

extension Sequence where Iterator.Element == UIView {
    func setHidden(_ hidden: Bool) {
        for view in self {
            view.isHidden = hidden
        }
    }
}

buttons.setHidden(true)
  1. Put the buttons inside a Stack View .

  2. Drag an outlet from that Stack View .

  3. Finally you will be able to use isHidden property on that Stack View .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM