我有一个方法,我正在创建 UIView,当我从 IBAction 调用它时它工作正常。但是当我再次调用相同的方法时,它会在顶部绘制另一个 View ,我相信这是内存泄漏。如何在创建另一个 UIView 之前删除之前的 UIView?谢谢!
- (int)showQuestionMethod:(int)number;
{
UIView *questionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 250)];
questionView.backgroundColor = [[UIColor alloc] initWithRed:0.93 green:0.93
blue:0.93 alpha:1.0];
[self.view addSubview:questionView];
questionView.tag = questionNumber;
UILabel *questionLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 280, 0)];
questionLabel.text = question1;
[questionView addSubview:questionLabel];
CGRect frame = questionView.frame;
frame.size.height = questionHeight;
questionView.frame = frame;
questionView.tag = questionNumber;
return currentQuestion;
}
- (IBAction)nextQuestion:(id)sender {
[self showQuestionMethod:questionNumber];
}
最佳答案
创建一个允许您引用 View 的属性:
@property(nonatomic, strong) UIView *questionView;
然后更改方法以删除旧 View 并创建新 View :
- (int)showQuestionMethod:(int)number;
{
// Remove the previous view.
[_questionView removeFromSuperview];
// Create a new view.
_questionView= [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 250)];
_questionView.backgroundColor = [[UIColor alloc] initWithRed:0.93 green:0.93
blue:0.93 alpha:1.0];
// Add the view.
[self.view addSubview:_questionView];
_questionView.tag = questionNumber;
UILabel *questionLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 280, 0)];
questionLabel.text = question1;
[_questionView addSubview:questionLabel];
CGRect frame = _questionView.frame;
frame.size.height = questionHeight;
_questionView.frame = frame;
_questionView.tag = questionNumber;
return currentQuestion;
}
关于ios - 在创建另一个 UIView 之前删除之前的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22077240/