1

I have a class in which I need to get a reference to one of the child views of my UIViewController, for example I need to change the text in every UIViewController from one swift class.

So this is my class:

class CustomClass: UIViewController {

   var button: UIView!

   func initClass(controller: UIViewController){
      button = controller.view.getViewByIdentifier("button")
   }

   func changeButtonText(){
      button.text = "changed!"
   }

}

with this call I can then initialize it in every UIViewController and change the text with only one method.

But how can I get the reference to the button in each view?

1 Answer 1

1

Enumerate all buttons in view and change their title. Functional swifty way:

    self.view.subviews.flatMap { (view) -> UIButton? in
        return view as? UIButton
    }.forEach { (button) -> () in
        button.setTitle("changed!", forState: .Normal)
    }

Little explantion: flatMap maps the array of subviews returning only UIButtons with optionals unwrapped. Then just set title for each of them.

Swift 1.2 (unchecked):

    self.view.subviews.map { (view) -> Void in
        if let button = view as? UIButton {
            button.setTitle("changed!", forState: .Normal)
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

it says: cannot invoke "foreach" with argument list of type (_) -> ()
Definitely. Swift 2.0 is the future, no sense to write in 1.2 now and then update that code to 2.0. Of course, unless you have a huge project to maintain. I'll post an example for 1.2, but don't have a possibility to check.

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.