iOS study Day 21-UIView 如何实现view的嵌套

来源:互联网 发布:php是一种什么型的语言 编辑:程序博客网 时间:2024/05/01 23:46
#define LINEHEIGHT 44.0#define TEXTTAG 10#import "WViewController.h"@interface WViewController ()@end@implementation WViewController- (void)viewDidLoad{    [super viewDidLoad];        }-(IBAction)deleteLast{            UIView* lastview = [self.view.subviews lastObject];    CGRect rect = lastview.frame;    rect.origin.x = self.view.frame.size.width;        [UIView animateWithDuration:0.5f animations:^{        [lastview setFrame:rect];            } completion:^(BOOL finished) {                [lastview removeFromSuperview];        _removeIt.enabled = [self.view.subviews count] > 3;    }];               }- (IBAction)newtext{    UIView* view = [self.view.subviews lastObject];        CGFloat y ;        // xcode 5.1中 默认会从中添加两个view  记住用法    [self.view.subviews count] == 3  ?( y = 44 ):( y = (view.frame.origin.y + view.frame.size.height +1 ));    CGFloat x = 0;        CGFloat width = self.view.frame.size.width ;        [UIImage imageNamed:[NSString stringWithFormat:@"%d", arc4random_uniform(8)]];        UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, LINEHEIGHT)];        UILabel* text = [[UILabel alloc] init];        // 经常要犯错,记得相对位置    [text setCenter:CGPointMake(width * 0.5 ,  LINEHEIGHT* 0.5) ];    [text setBounds:CGRectMake(0, 0, 200, LINEHEIGHT)];    [text setBackgroundColor:[UIColor clearColor]];        [text setText:[NSString stringWithFormat:@"the mac has %d subview", [self.view.subviews count]]];        [text setTag:TEXTTAG];    [subview addSubview:text];                                                                    //arc4random_uniform(8) 生成【0 ~ 8】之间的任意整数    UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"%d",arc4random_uniform(8)]];    UIImage *img2 = [UIImage imageNamed:[NSString stringWithFormat:@"%d",arc4random_uniform(8)]];        UIButton* imgbtn = [[UIButton alloc] init];        [imgbtn setCenter:CGPointMake(20, LINEHEIGHT * 0.5)];        [imgbtn setBounds:CGRectMake(0, 0, img.size.width, img.size.height)];        [imgbtn setBackgroundImage:img forState:UIControlStateNormal];    [imgbtn setBackgroundImage:img2 forState:UIControlStateHighlighted];        [imgbtn addTarget:self action:@selector(clickbtn:) forControlEvents:UIControlEventTouchUpInside];        [subview addSubview:imgbtn];        subview.backgroundColor = [UIColor brownColor];    CGRect frame = subview.frame;        frame.origin.x = width;        [self.view addSubview:subview];    [subview setFrame:frame];    frame.origin.x = 0;    [UIView beginAnimations:nil context:nil];    [UIView setAnimationDuration:0.7f];    [subview setFrame:frame];    [UIView commitAnimations];        _removeIt.enabled = YES;}- (IBAction)clickbtn:(id)sender{    UIButton* btn = (UIButton*)sender;    UILabel* label = (UILabel*)[btn.superview viewWithTag:TEXTTAG];    NSLog(@"%@", label.text);}@end

0 0
原创粉丝点击