Basically, I have a quiz app where I add have questions, then switch to a different screen to show an expanded version of the correct answer after it is chosen. I've tried adding button and labels, but when I do this, I eventually end up with buttons and labels 'ghosting' on the screen, after I went them gone. How can I remove all subviews, so that each button and label I add from within a method appears on a fresh screen?
class MyApplicationController < UIViewController
def loadView
self.view = UIImageView.alloc.init
end
def viewDidLoad
super
view.userInteractionEnabled=true
@question_index=0
@answerChoices = []
@questionChoices=["What is best in life?",...]
makeQuestion
end
def makeQuestion
left =20
top=100
label = UILabel.new
label.text =@questionChoices[@question_index]
label.textAlignment = UITextAlignmentCenter
label.textColor = UIColor.redColor
label.frame = [[20,20], [view.frame.size.width-40, 40]]
label.lineBreakMode = UILineBreakModeWordWrap
label.numberOfLines = 0
label.sizeToFit
view.image = UIImage.imageNamed('background.jpg')
view.addSubview(label)
4.times do |i|
@button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
@button.setTitle(@answerChoices[i][@question_index], forState:UIControlStateNormal)
@button.frame = [[left, top], [view.frame.size.width - left * 2, 40]]
@button.addTarget(self, action:'actionTapped:', forControlEvents:UIControlEventTouchUpInside)
@button.tag=i
top+=45
view.addSubview(@button)
end
end
def makeAnswer
@button.removeFromSuperview
@button.removeFromSuperview
@button.removeFromSuperview
@button.removeFromSuperview
view.image = UIImage.imageNamed('back.jpg')
label = UILabel.new
label.text =@rightArray[@question_index]
label.textAlignment = UITextAlignmentCenter
label.textColor = UIColor.blackColor
label.frame = [[20,20], [view.frame.size.width-40, 40]]
label.lineBreakMode = UILineBreakModeWordWrap
label.numberOfLines = 0
label.sizeToFit
view.addSubview(label)
@button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
@button.setTitle("More questions", forState:UIControlStateNormal)
@button.tag=1
@button.addTarget(self, action:'makeQuestion', forControlEvents:UIControlEventTouchUpInside)
@button.frame = [[20, 100], [view.frame.size.width - 20 * 2, 40]]
view.addSubview(@button)
end
end
You need an array of buttons. In your 4.times
loop, you are overwriting the instance variable @button
four times. Instead, make @button an array of buttons, and assign a different button to each index.
If you have a variable myView
and want to remove all of its subviews, I believe this will work:
myView.subviews.each {|sv| sv.removeFromSuperview}