@interface ViewController () - (IBAction)removeAddLabel:(id)sender; @property (strong, nonatomic) IBOutlet UILabel *myLabel; @end
参照の種類を「strong」にします。
- (IBAction)removeAddLabel:(id)sender { if ([_myLabel isDescendantOfView:self.view]) { //viewから削除 [_myLabel removeFromSuperview]; }else{ //viewに追加 [self.view addSubview:_myLabel]; } }
参照を「strong」にしておくと、そのUIを管理するViewControllerが削除されても、UIは生き続けます。上のコードは、「isDescendantOfView」で指定したUILabelのインスタンスが、引数のviewと子孫かどうかをチェックしています。それからviewにあったら削除、なかったら追加をしています。