skip to Main Content

In Swift, I have a view with three objects. I want the button and label to be on top of the image. This is a concept like maybe layers in Photoshop. Currently, the image is on top of the button and label, so you can not see the button and label. How is this done?

My code is here:

import UIKit

    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            let myFirstLabel = UILabel()
            let myFirstButton = UIButton()
            let myFirstImage = UIImage(named: "1792614.jpg")
            let myFirstImageView = UIImageView(image: myFirstImage)

            myFirstLabel.text = "I made a label on the screen #toogood4you"
            myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
            myFirstLabel.textColor = UIColor.redColor()
            myFirstLabel.textAlignment = .Center
            myFirstLabel.numberOfLines = 5
            myFirstLabel.frame = CGRectMake(15, 54, 300, 500)

            myFirstButton.setTitle("✸", forState: .Normal)
            myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
            myFirstButton.frame = CGRectMake(160, 284, 50, 50)
            myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)

            self.view.addSubview(myFirstLabel)
            self.view.addSubview(myFirstButton)
            self.view.addSubview(myFirstImageView)
        }

        func pressed(sender: UIButton!) {
            var alertView = UIAlertView()
            alertView.addButtonWithTitle("Ok")
            alertView.title = "title"
            alertView.message = "message"
            alertView.show()
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }


    }

2

Answers


  1. You’re adding the views in this order:

    self.view.addSubview(myFirstLabel)
    self.view.addSubview(myFirstButton)
    self.view.addSubview(myFirstImageView)
    

    which means myFirstImageView is going to be on top. Reversing the order of the addSubview calls will do what you want.

    Login or Signup to reply.
  2. The answer is here:

    self.view.addSubview(myFirstLabel)
    self.view.addSubview(myFirstButton)
    self.view.addSubview(myFirstImageView)
    

    When you add a subview, it always gets put at the top, to achieve what you want, add the view you want at the bottom first, and the one you want on top last:

    self.view.addSubview(myFirstImageView)
    self.view.addSubview(myFirstButton)
    self.view.addSubview(myFirstLabel)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search