Reputation: 647
I am creating a custom UIView
that should contain a UIImageView
and a UILabel
here is the class for it.
import UIKit
class AnswersCustomView: UIView {
var myImageView = UIImageView()
var myLabel = UILabel()
override init (frame : CGRect) {
super.init(frame : frame)
backgroundColor = UIColor.blueColor()
addLabel()
bringSubviewToFront(myLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func addLabel(){
let myViewFrame = self.frame
myLabel.frame = myViewFrame
myLabel.backgroundColor = UIColor.redColor()
myLabel.center=self.center
addSubview(myLabel)
}
}
whenever I create an instance of this view from a UIViewController
.
the UIView
get added but it seems that the UILabel
is not.
any reason for that?
Upvotes: 0
Views: 468
Reputation: 26385
As already pointed out in the comment one problem could be that the label has an incorrect frame.
As stated in Apple documentation the frame is:
This rectangle defines the size and position of the view in its superview’s coordinate system. You use this rectangle during layout operations to size and position the view. Setting this property changes the point specified by the center property and the size in the bounds rectangle accordingly. The coordinates of the frame rectangle are always specified in points.
The label you created is subview of the instance AnswersCustomView
, not the AnswersCustomView
superview, so you should set the label's frame as its superview bounds.
The other one is autolayout: you are not using it. I don't know how you create the AnswerView, bit if its initial frame is zero your label will remain zero, you should add it and set constraints or at least autoresizing masks.
Another one can be if you are creating the view in a xib, in this case iniWithCoder
is called and here you are not placing any label.
To simplify views debugging Apple has added a new tool that displays your view hierarchy in 3d https://www.raywenderlich.com/98356/view-debugging-in-xcode-6
Upvotes: 1