上QQ阅读APP看书,第一时间看更新
实例023 设置视图位置互换显示(2)
实例说明
在iOS应用中,可以使用UIView的tag属性为某个视图设置一个标签,这样在具体操作时可以直接调用这个tag,就相当于调用了这个视图。例如,在程序里有一个顶层容器UIView,我们可以在它上面进行多个子UIImageView的添加和删除操作。在添加的时候,可以为每个子UIImageView添加一个tag(大于0的整数)。接下来如何进行删除视图的操作,可以先通过顶层UIView的subviews方法,得到所有子UIImageView,然后根据指定的tag删除UIView上对应的子UIImageView。由此可见,tag起了一个标签的作用。
本实例的功能是设置了10个视图,并为每个视图设置了对应的tag。其中将第8个视图的tag设置为999。在下方设置了一个“search 999”按钮,当单击此按钮后会检索显示出值为999的视图。
具体实现
实例文件UIkitPrjTag.h的实现代码如下所示。
#import "SampleBaseController.h" @interface UIKitPrjTag : SampleBaseController { @private UILabel* parent_; } @end
实例文件UIkitPrjTag.m的实现代码如下所示。
#import "UIKitPrjTag.h" #pragma mark ----- Private Methods Definition ----- @interface UIKitPrjTag () - (void)searchDidPush; @end #pragma mark ----- Start Implementation For Methods ----- @implementation UIKitPrjTag // finalize - (void)dealloc { [parent_ release]; [super dealloc]; } - (void)viewDidLoad { [super viewDidLoad]; // 背景设置成黑色 self.view.backgroundColor = [UIColor blackColor]; // 追加父标签 parent_ = [[UILabel alloc] initWithFrame:CGRectMake( 0, 0, 320, 320 )]; parent_.textAlignment = UITextAlignmentCenter; parent_.text = @"PARENT"; [self.view addSubview:parent_]; // 追加10个子标签 for ( int i = 1; i <= 10; ++i ){ UILabel* child = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease]; child.text = [NSString stringWithFormat:@"CHILD %d", i]; [child sizeToFit]; CGPoint newPoint = child.center; newPoint.y += 30 * i; child.center = newPoint; [parent_ addSubview:child]; // 将第8个标签的tag设置成999 if ( 8 == i ) { child.tag = 999; } } // 追加search按钮 UIButton* searchButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; searchButton.frame = CGRectMake( 0, 0, 150, 40 ); CGPoint newPoint = self.view.center; newPoint.y = self.view.frame.size.height -40; searchButton.center = newPoint; [searchButton setTitle:@"search 999" forState:UIControlStateNormal]; [searchButton addTarget:self action:@selector(searchDidPush) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:searchButton]; } #pragma mark ----- Private Methods ----- - (void)searchDidPush { NSString* message; //从parent_的子元素中检索tag为999的元素,找到后显示警告框 UILabel* label = (UILabel*)[parent_ viewWithTag:999]; if ( label ) { message = label.text; } else { message = @"nothing"; } UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"search 999" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil ] autorelease]; [alert show]; } - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { [self.navigationController setNavigationBarHidden:NO animated:YES]; } @end
执行后的效果如图2-27所示。
图2-27 执行效果