And in your iOS applications, IBOutlet is already private?

    image

    You have probably used Storyboard or XIB for layout of interfaces? To make up from the code is fine, but sometimes it is much easier to understand how some of the components of the interface are arranged, after seeing it, and not after reading it. In this post, I want to discuss the need to use the private modifier for IBOutlet.

    Developers for whom the IBOutlet encapsulation is obvious are unlikely to be surprised, but a survey at the end of the article may be interesting.

    Imagine that you are going to create an IBOutlet (link to View from the Storyboard) for one of your UILabels. When dragging with the mouse, Xcode will carefully create something like

    @IBOutletweakvar myLabel: UILabel!

    For a long time I considered this construction optimal, until my colleague didn’t ask - why isn’t your IBOutlet private?

    In fact, why should I leave all IBOutlets accessible from the outside?
    Imagine a classic task - we have a cell in which, for example, someone’s contact is displayed

    import UIKit
    classContactCell: UITableViewCell{
        @IBOutletprivateweakvar nameLabel: UILabel!@IBOutletprivateweakvar positionLabel: UILabel!overridefuncawakeFromNib() {
            super.awakeFromNib()
        }
        funcsetupCell(withContact contact: Contact) {
            nameLabel.text = contact.name
            positionLabel.text = contact.position
        }
    }

    By adding private to our familiar IBOutlet, we can ensure that the specified cell fields will not be specified from another class. This can be especially useful during teamwork, when someone, due to negligence / lack of time / stupidity (underline the necessary), will try to set colors, text or some other properties in the Label cells directly in the tableView method (_: cellForRowAt :) .

    Imagine that a cell or a whole ViewController contains a lot of IBOutlets, that there are a lot of display settings. Isn't it easier to protect yourself by adding private, than to search then why the appearance of the element suddenly changed or did Gesture Recognizer appear from somewhere, which sets an unexpected behavior?

    PS: If after reading you want to use private for IBOutlets, then for simplicity, you can get a snippet for this in Xcode.

    Below is a poll, if you want to comment on your answer, welcome in the comments.

    Only registered users can participate in the survey. Sign in , please.

    How do you generally prefer to set an IBOutlet?


    Also popular now: