1

基本上,我有一个测验应用程序,我在其中添加问题,然后切换到不同的屏幕以在选择正确答案后显示正确答案的扩展版本。我试过添加按钮和标签,但是当我这样做时,我最终会在屏幕上出现按钮和标签“重影”,在我离开它们之后。如何删除所有子视图,以便我从方法中添加的每个按钮和标签出现在新屏幕上?

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
4

1 回答 1

3

您需要一系列按钮。在您的4.times循环中,您将覆盖实例变量@button四次。相反,将@button 设为按钮数组,并为每个索引分配不同的按钮。

如果您有一个变量myView并想删除它的所有子视图,我相信这会起作用:

myView.subviews.each {|sv| sv.removeFromSuperview}
于 2012-09-22T17:55:56.187 回答