티스토리 뷰

반응형


Tag값을 이용한 객체 속성 변경하기.


전역변수로 설정하지 않더라도 Tag를 이용해 객체의 속성을 변경할 수 있다.

단 객체가 addSubView된 객체는 전역으로 설정되어 있어야 한다.

객체는 어떠한 것도 가능하며 캐스팅해주어야 한다. (객체타입)[뷰 viewWithTag:??]

다음 예제는 View에 UIButton, UIimageView를 생성하고, Button 선택 시 ImageView의 backgroundColor를 교체해주는 소스이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 
//팝업 생성.
-(void)createPopup
{
    popupView = [[UIView alloc] initWithFrame:CGRectMake(1200200200)];
    [self.view addSubview:popupView];
    popupView.center = self.view.center;
    
    float height = 40.0f;
    
    for (int i = 0; i<5; i++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(0, (i*height), popupView.frame.size.width, height)];
        [btn setBackgroundColor:[UIColor redColor]];
        [btn setTitle:@"button" forState:UIControlStateNormal];
        [btn setAlpha:0.2f];
        [btn addTarget:self action:@selector(selectButton:) forControlEvents:UIControlEventTouchUpInside];
        [popupView addSubview:btn];
        [btn setTag:i];
        
        //Tag를 통한 객체 변경.
        UIImageView *tempView = [[UIImageView alloc] initWithFrame:CGRectMake(150, btn.frame.origin.y, 50, height)];
        [tempView setBackgroundColor:[UIColor redColor]];
        [popupView addSubview:tempView];
        [tempView setTag:(btn.tag+100)];
    }
}
 
//색상값 변경.
-(void)selectButton:(UIButton *)btn
{
    //popupView 에서 tag값에 해당하는 객체를 가져온다.
    UIImageView *tempView = (UIImageView *)[popupView viewWithTag:(btn.tag+100)];
    
    //상태에 맞게 값 변경.
    if (tempView.backgroundColor == [UIColor redColor] )
    {
        [btn setTitle:@"select" forState:UIControlStateNormal];
        [tempView setBackgroundColor:[UIColor orangeColor]];
    }else{
        [btn setTitle:@"button" forState:UIControlStateNormal];
        [tempView setBackgroundColor:[UIColor redColor]];
    }
}
 
cs


반응형
댓글
반응형