1

I'm trying to make an array of UI elements, but with different types inside. Some are image views, and some are buttons. I am familiar with making a collection of the same type, such as

@IBOutlet var things: [UIButton]!

but that code only makes an array of buttons, while I need to add image views to that also. How can I make an array that accepts both types?

1
  • Note that this can't be an IBOutlet. Do you mean to mark it IBOutletCollection, or did you add that by accident? Commented May 10, 2017 at 21:42

2 Answers 2

3

Just use array of UIViews. var arrayOfThings : [UIView]

Sign up to request clarification or add additional context in comments.

Comments

2
 @IBOutlet weak var view2: UIView!

var uiElements:[UIView] = []

override func viewDidLoad() {
    super.viewDidLoad()

    let button1 = UIButton()
    let image1 = UIImageView()

    uiElements.append(button1)
    uiElements.append(image1)
    uiElements.append(view2)

    for element in uiElements {

        if element is UIButton {
            print("it's a button")
        } else if element is UIImageView {
            print("it's imageview")
        } else if element is UIView {
            print("it's uiview")
        } else {
            print("error")
        }
    }
 }

Output:
it's a button
it's imageview
it's uiview

1 Comment

Why use AnyObject? Use UIView since it is an array of views.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.