在Swift中,我有一个包含三个对象的视图。我希望按钮和标签位于图像的顶部。这是一个像Photoshop中的图层一样的概念。目前,图像位于按钮和标签的顶部,因此您无法看到按钮和标签。这是怎么做到的?
我的代码在这里:
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.
}
}
答案 0 :(得分:8)
答案在这里:
self.view.addSubview(myFirstLabel)
self.view.addSubview(myFirstButton)
self.view.addSubview(myFirstImageView)
当您添加子视图时,它总是放在顶部,以实现您想要的效果,首先在底部添加您想要的视图,然后在最后一个添加您想要的视图:
self.view.addSubview(myFirstImageView)
self.view.addSubview(myFirstButton)
self.view.addSubview(myFirstLabel)
答案 1 :(得分:0)
您按此顺序添加了视图:
self.view.addSubview(myFirstLabel)
self.view.addSubview(myFirstButton)
self.view.addSubview(myFirstImageView)
这意味着myFirstImageView
将成为最重要的。颠倒addSubview
来电的顺序可以达到你想要的效果。