J-Dizzle
J-Dizzle

Reputation: 5143

How to add a UIView into another UIView at the bottom

How do you insert a UIView into a UILabel?

Goal:

Make a separate UIView the background of an existing UI component.

Example

    //Views
    let viewOne = UIImageView(); //bottom view, e.g. a UIImageView
    let viewTwo = UILabel();     //top view, e.g. a UILabel

    //Traditional
    self.addSubview(viewOne);
    self.addSubview(viewTwo);   //viewTwo goes on top 

    //Target
    viewTwo.addSubview(viewOne);
    self.addSubview(viewTwo;    //goal is to encapsulate viewOne into viewTwo

Question

How do you insert viewOne into the bottom of viewTwo? Do you use a layer of viewOne, I can't seem to get this successful!

Upvotes: 0

Views: 352

Answers (2)

J-Dizzle
J-Dizzle

Reputation: 5143

thank you Adam, I used this for solution. For reference here is my solution:

class TexturedLabel :  NSObject {
    var label     : UILabel;
    var imageView : UIImageView;

    override init() {
        label     = UILabel();
        imageView = UIImageView();
        super.init();
        imageView.image = UIImage(named:"textured");  /* grab texture img                                   */
        imageView.contentMode = .topLeft;             /* place the image in the upper left corner unscaled  */
        imageView.clipsToBounds = true;               /* constrain image to frame boundaries                */
    }

    func text(_ text:String)                            { label.text = text; }
    func font(_ font:UIFont?)                           { label.font = font; }
    func color(_ color:UIColor)                         { imageView.backgroundColor = color;
    func frame(_ frame:CGRect)                          { label.frame = frame; imageView.frame = frame; }    
    func textColor(_ textColor:UIColor)                 { label.textColor = textColor; }
    func textAlignment(_ textAlignment:NSTextAlignment) { label.textAlignment = textAlignment; }
    func numberOfLines(_ numberOfLines:Int)             { label.numberOfLines = numberOfLines; }
    func lineBreakMode(_ lineBreakMode:NSLineBreakMode) { label.lineBreakMode = lineBreakMode; }

    func addToView(_ view : UIView) {
        view.addSubview(self.imageView);
        view.addSubview(self.label);
    }
}

Thank you so much Adam!!

Upvotes: 0

Adam Kaplan
Adam Kaplan

Reputation: 1962

As a general rule, you should not use UIKit classes in un-documented or unexpected ways if it can be avoided. In this case, you don't know if UILabel expects a specific set of subviews, or if it depends on the order of those subviews.

The correct way to do this is to make new UIView subclass that contains both views as it's own subviews. This way, you can control the view order, position, etc without worrying about how UILabel internals may change in the future.

Upvotes: 3

Related Questions