iosxcodeviewreceiversuperview

Could you explain "receiver" and "view - superview" in Swift?


override func draw(_ rect: CGRect) {

    let size: CGFloat = 20
    let currencyLbl = UILabel(frame: CGRect(x: 5, y: (frame.size.height/2) - size, width: size, height: size))
    currencyLbl.backgroundColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 0.5)
    currencyLbl.textAlignment = .center
    currencyLbl.textColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
    currencyLbl.layer.cornerRadius = 5.0
    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.locale = .current
    currencyLbl.text = formatter.currencySymbol
    addSubview(currencyLbl)

}

addSubview's explanation in Xcode is "Adds a view to the end of the receiver’s list of subviews" and it says "This method establishes a strong reference to view and sets its next responder to the receiver, which is its new superview "

Could you explain "receiver" and "view - superview" in that context.


Solution

  • "receiver" is a throwback to the days of objective-c when "messages" were sent to "objects". So us old people (hah) used to call [someView addSubview:anotherView] instead of someView.addSubview(anotherView). In that scenario, "someView" is the receiver because it's RECEIVING the "addSubview" message.

    Views are stored in hierarchies, a tree basically, where each view can have many children (subviews), but only one parent (superview). In my example, "someView" is the superView (parent) in which "anotherView" will be added as a subview (child).

    In your sample, the class you are implementing there is both the receiver AND the superview. It's the receiver because your addSubview call is implicitly "self.addSubview" which means "self" is the receiver. It's the super view because currencyLbl is being added to it as a subview.

    Spelled out explicitly for your exact case:

    (Note - Receiver and Superview are not synonyms, they just happen to refer to the same object in this case. They are completely unrelated concepts.)