Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - How to reference views in view controller?

Tags:

ios

swift

From an android background, each UI Element (i.e., "widget") has an id. For example, userNameInputText could be an id that maps to a specific text field. What is the analog for iOS?

In Xcode, I define views in my storyboard, then ctrl+drag them to my ViewController class. This allows me to set up listeners, etc. However, it seems that something is being obscured. How does the listener reference back to the specific view? In android this would be obvious because you must explicitly provide the element's id.

like image 257
another_user10293412 Avatar asked Mar 13 '23 07:03

another_user10293412


2 Answers

I define views in my storyboard, then ctrl+drag them to my ViewController class. This allows me to set up listeners, etc

Control-drag not only allows you to add listeners. It also allows you to add outlet connections. An outlet connection looks like this in code:

@IBOutlet var myUIElement: UIXXXX!

You can use the identifier myUIElement to reference the view. Here's an example of how to add an outlet connection:

  • Control-drag a view, say UIImageView to the View Controller class and this appears:

enter image description here

See the word "Outlet" there? That means you are adding an outlet connection. And let's call the outlet myImage. So in code, this will look like this:

@IBOutlet weak var myImage: UIImageView!

And now you have a reference to the image view in your storyboard! Just like in Java, but shorter. Let me write this in Java so you get a clearer picture:

private ImageView myImage;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setLayout(R.layout.someLayout);
    myImage = (ImageView)findViewById(R.id.someId);
}

If you want to get back a prototype table view cell, there's another method:

  • In the storyboard, select the cell, and add a reuse identifier to the cell, say my cell.
  • In the table view controller, call this method:

    let cell = tableView.dequeueReusableCellWithIdentifier("my cell")
    

And now you can get the cell!

like image 151
Sweeper Avatar answered Mar 23 '23 04:03

Sweeper


If you view the content of a xib file, you will find something like
<view contentMode="scaleToFill" id="iN0-l3-epB">

So I think xCode uses generated identifiers to connect these views to your IBOutlets.

like image 38
Ahmad Baraka Avatar answered Mar 23 '23 04:03

Ahmad Baraka