ios - 在创建另一个 UIView 之前删除之前的 UIView

标签 ios objective-c uiview

我有一个方法,我正在创建 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/

相关文章:

ios - 圆形 UITableViewCell 仅底部或顶部角,但它不适用于 Swift iOS 10

ios - 快速拍摄黑色图像

objective-c - 如何使用 CUPS 查找打印机 URI

swift - 混合程序化和 IB 设计时查看元素未显示

javascript - Swift - 动画矩形

ios - 在 RxSwift 中解析 JSON 并处理来自 API 的错误响应

ios - SKPhysicsJointPin 引脚位置

ios - 手写绘图有点晚,就像我手指的回声 ios objective c

ios - 从 UIView 调用共享表

ios - 使用后台线程更新界面的更快方法