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
You’re adding the views in this order:
which means
myFirstImageView
is going to be on top. Reversing the order of theaddSubview
calls will do what you want.The answer is here:
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: