當我的應用程序按鈕被按下時,它會調用addSubView()
在我的ViewController的超級視圖中添加一個新視圖。問題是,有2個按鈕來移動2個其他視圖100x100在這個相同的超視圖,當我調用addSubView(newView),我的其他2視圖的位置重置爲原點。爲什麼.addSubView(...)方法在使用時重置其他對象位置?
我的問題是,我如何添加一個保存其他視圖座標的新視圖?
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var bloco1: UIView!
@IBOutlet weak var bloco2: UIView!
@IBOutlet weak var botao1: UIButton!
@IBOutlet weak var botao2: UIButton!
var bloco1Origem: CGPoint!
var bloco2Origem: CGPoint!
var corBlocos: UIColor!
var reprodutorDeAudio: AVAudioPlayer?
var somDoAlerta: NSURL!
var novaView: UIView!
var qntBlocosNovos = 0
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("SomDeColisão", ofType: "mp3")
somDoAlerta = NSURL(fileURLWithPath: path!)
do {
reprodutorDeAudio = try AVAudioPlayer(contentsOfURL: somDoAlerta)
reprodutorDeAudio!.prepareToPlay()
} catch {
print(error)
}
}
override func viewWillAppear(animated: Bool) {
bloco1.backgroundColor = corBlocos
bloco2.backgroundColor = corBlocos
}
override func viewDidAppear(animated: Bool) {
bloco1Origem = bloco1.frame.origin
bloco2Origem = bloco2.frame.origin
}
@IBAction func AddNovoBloco(sender: UIBarButtonItem) {
novaView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
novaView.backgroundColor = UIColor.yellowColor()
self.view.addSubview(novaView)
//self.view.didAddSubview(novaView)
++qntBlocosNovos
}
@IBAction func botao(sender: UIButton) {
bloco1.frame.origin.x += 10
if colisao() {
bloco2.backgroundColor = UIColor.redColor()
botao1.enabled = false
botao2.enabled = false
}
// view2.transform = CGAffineTransformMakeRotation(10)
}
@IBAction func excluirTodos(sender: UIButton) {
while qntBlocosNovos > 0 {
(view.subviews.last! as UIView).removeFromSuperview()
--qntBlocosNovos
}
}
@IBAction func botao2(sender: UIButton) {
if qntBlocosNovos > 0 {
(view.subviews.last! as UIView).removeFromSuperview()
}
bloco2.frame.origin.x -= 10
if colisao() {
bloco1.backgroundColor = UIColor.redColor()
botao1.enabled = false
botao2.enabled = false
}
}
func colisao() -> Bool {
if CGRectIntersectsRect(bloco1.frame, bloco2.frame) {
guard let rep = reprodutorDeAudio else {
return true
}
rep.play()
return true
}
return false
}
@IBAction func Reinicia(sender: UIButton) {
bloco1.frame.origin = bloco1Origem
bloco2.frame.origin = bloco2Origem
botao1.enabled = true
botao2.enabled = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
請發表您的代碼 – Lamar
只是增加了它:) – Renan