基本上,我有一个测验应用,我添加了问题,然后切换到另一个屏幕,以显示选择后正确答案的扩展版本。我尝试过添加按钮和标签,但是当我这样做时,我最终会在屏幕上显示按钮和标签“重影”,之后我就不再使用了。如何删除所有子视图,以便我在方法中添加的每个按钮和标签都会显示在新屏幕上?
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
答案 0 :(得分:3)
您需要一组按钮。在4.times
循环中,您将覆盖实例变量@button
四次。相反,将@button设为一个按钮数组,并为每个索引指定一个不同的按钮。
如果你有一个变量myView
并想要删除它的所有子视图,我相信这会有效:
myView.subviews.each {|sv| sv.removeFromSuperview}