26

プログラムでビューにサブビューとしてUIButtonとUITextViewを追加しました。

notesDescriptionView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,460)];
notesDescriptionView.backgroundColor = [UIColor redColor];
[self.view addSubview:notesDescriptionView];

textView = [[UITextView alloc] initWithFrame:CGRectMake(0,0,320,420)]; 
[self.view addSubview:textView]; 
printf("\n description  button \n");

button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button
  addTarget:self action:@selector(cancel:)
  forControlEvents:UIControlEventTouchDown];
[button setTitle:@"OK" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 420.0, 160.0, 40.0);
[self.view addSubview:button];

ボタンがクリックされたときにすべてのサブビューを削除する必要があります。

私が試してみました:

[self.view removeFromSuperView]

しかし、それは機能していません。

4

3 に答える 3

59

ビューに追加したすべてのサブビューを削除します

次のコードを使用します

for (UIView *view in [self.view subviews]) 
{
    [view removeFromSuperview];
}
于 2010-06-09T12:49:32.490 に答える
23

[self.view removeFromSuperView]上記のスニペットと同じクラスのメソッドから呼び出していると仮定します。

その場合[self.view removeFromSuperView]、self.viewはそれ自体のスーパービューから削除されますが、selfは、サブビューを削除するビューのオブジェクトです。オブジェクトのすべてのサブビューを削除する場合は、代わりにこれを行う必要があります。

[notesDescriptionView removeFromSuperview];
[button.view removeFromSuperview];
[textView removeFromSuperview];

おそらく、これらのサブビューをに格納し、その配列の各要素をNSArray呼び出すその配列をループする必要があります。removeFromSuperview

于 2010-06-09T12:05:43.793 に答える
8

Objective-C APIには、UIViewからすべてのサブビューを削除するための簡単な方法がないことにいつも驚いています。(Flash APIはそうです、そしてあなたはそれをかなり必要とすることになります。)

とにかく、これは私がそのために使用する小さなヘルパーメソッドです:

- (void)removeAllSubviewsFromUIView:(UIView *)parentView
{
  for (id child in [parentView subviews])
  {
    if ([child isMemberOfClass:[UIView class]])
    {
      [child removeFromSuperview];
    }
  }
}

編集:ここでよりエレガントな解決策を見つけました:self.viewからすべてのサブビューを削除するための最良の方法は何ですか?

現在、次のように使用しています。

  // Make sure the background and foreground views are empty:
  [self.backgroundContentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
  [self.foregroundContentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

私はそれがもっと好きです。

于 2014-02-21T06:07:03.110 に答える