본문 바로가기
옛날

[ios] 자주 쓰는 패턴

by 차가운게 조아 2016. 9. 5.
//background 배경이미지 넣기 
1
2
3
4
5
self.view.backgroundColor =
    [UIColor colorWithPatternImage:
        [UIImage imageWithContentsOfFile:
            [[[NSBundle mainBundle] resourcePath]
                stringByAppendingPathComponent:@"intro_bg_01.png"]]];


//UIImage UIimageView 이미지 붙이기 
1
2
3
4
5
6
UIImage *img = [UIImage imageNamed:@"notice_bg.png"];
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[imgView setFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
[self.view addSubview:imgView];
[img release];
[imgView release];


//UIImage UIButton 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
UIImage *img = [UIImage imageNamed:@"res_btn_01.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
 
button.frame =
    CGRectMake(230, 100/2 -img.size.height/2,
        img.size.width, img.size.height);
 
[button addTarget:self
    action:@selector(infoAction)
    forControlEvents:UIControlEventTouchUpInside];
     
[button setImage:img forState:UIControlStateNormal];
[button setImage:img forState:UIControlStateHighlighted];
[cell addSubview:button];


//UILabel 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int x=0;
int y=0;
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(x, y, 100, 100)];
 
// label.textColor =
// [UIColor colorWithRed:136/255.0 green:112/255.0 blue:79/255.0 alpha:1];
 
label.text = [[dataArray objectAtIndex:indexPath.row] objectForKey:@"time"];
 
// label.font = [UIFont systemFontOfSize:13.0f];
 
[label setNumberOfLines:0];
 
//길면 줄 바꿈됨
[label setLineBreakMode:UILineBreakModeWordWrap];
 
[self.view addSubview:label];
label.backgroundColor = [UIColor clearColor];


//event 
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
- (void) buttonAction:(id)sender {
    NSLog(@"click");
 
    UIButton *button = (UIButton*)sender;
 
    switch (button.tag) {
        //대기중
        case 0:
            [self setWaitingData];
            break;
 
        //완료된 면접
        case 1:
            [self setDoneData];
            break;
 
        default:
            break;
    }
}
 
- (void) toggleMenuAction {
    toggleView = !toggleView;
     
    for (UIButton *button in self.view.subviews) {
        if(button!=nil && [button isKindOfClass:[UIButton class]]
            && (button.tag==0 || button.tag==1 || button.tag==2 )) {
            button.hidden = toggleView;
        }
    }
 
    // [closeButton removeFromSuperview];
    menuButton.selected = toggleView;
}


//UIScrollView는 self.view에 붙여야 한다.
UIView를 상속붙은 콤포넌트들(UIImageView 등등) 에 붙이면안그럼 스크롤 안붙는다.
1
2
3
4
5
UIScrollView *scView =
    [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 480, 320)];
[scView setScrollEnabled:YES];
[scView setContentSize:CGSizeMake(2000, 500)];
[self.view addSubview:scView];


//네비게이션 색상 바꾸기 (하나의 클래스 안에 선언하면 모든 클래스에 적용된다) 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    //이미지
    // UIImage *image = [UIImage imageNamed: @"menu_big_bg_01_r.png"];
    // [image drawInRect:
    // CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
 
    //배경 색깔 (베니 바탕만 바뀐다)
    // UIColor *color = [UIColor blackColor];
    // CGContextRef context = UIGraphicsGetCurrentContext();
    // CGContextSetFillColor(context,
    //     CGColorGetComponents( [color CGColor]));
    // CGContextFillRect(context, rect);
 
 
    //버튼과 네비 배경까지 검은색으로 다 바뀐다
    [self setTintColor:[UIColor colorWithRed:0.0f
        green: 0.0f
        blue:0.0f
        alpha:1]];
}


//네비게이션 바 뒤로 가기 
1
[self.navigationController popToRootViewControllerAnimated:YES];


//네비게이션 바 이름 
1
2
3
4
5
6
// self.title = @"대입정보";
self.navigationItem.title = @"대입정보";
 
self.title = @"대입정보";
// 으로 하면 tabbar에도 이름이 들어간다.
// 만약 커스텀 탭바에서 이것 쓰면 낭패~


//네비게이션바 숨기기
1
2
3
- (void) viewWillAppear:(BOOL)animated {
    [[self navigationController] setNavigationBarHidden:YES animated:NO];
}



//네비게이션바 보이기
1
2
3
- (void) viewWillAppear:(BOOL)animated {
    [[self navigationController] setNavigationBarHidden:NO animated:YES];
}


//네비게이션바 이름
1
self.navigationItem.title = @"대입정보";


//네비게이션바 푸쉬
1
[self.navigationController pushViewController:listViewController animated:YES];


//alert
1
2
3
4
5
6
7
UIAlertView* alert = [[UIAlertView alloc]
    initWithTitle:@"수강신청 완료"
    message:@"수강신청이 완료 되었습니다."
    delegate:self cancelButtonTitle:@"확인" otherButtonTitles:nil, nil];
 
[alert show];
[alert release];


//UITalbeView
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#import <UIKit/UIKit.h>
 
@interface PortfolioChangeViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource>
{
    UITableView *listTableView;
    NSMutableArray *tableDataArray;//뿌려줄데이타들(검색결과 && 원본 깊은복사본)
    int cellCount;
    int more;
    int heightCell;
}
- (void) setData:(int)num;
@end
 
 
#import "PortfolioChangeViewController.h"
 
@implementation PortfolioChangeViewController
 
- (id)initWithNibName:(NSString *)nibNameOrNil
    bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     
    if (self) {
        // Custom initialization
    }
    return self;
}
 
- (void)dealloc
{
    [super dealloc];
}
 
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
 
    // Release any cached data, images, etc that aren't in use.
}
 
#pragma mark - View lifecycle
 
/*
// Implement loadView to create a view hierarchy programmatically,
// without using a nib.
- (void)loadView
{
}
*/
 
// Implement viewDidLoad to do additional setup after loading the view,
// typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
     
    self.navigationItem.title = @"포트폴리오 변경";
    heightCell = 3+3+43;
 
    //table
    listTableView =
        [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 377)];
         
    [listTableView setDelegate:self];
    [listTableView setDataSource:self];
    [listTableView setScrollEnabled:YES];
    [listTableView setAutoresizesSubviews:YES];
    listTableView.backgroundColor = [UIColor clearColor];
    listTableView.separatorStyle = YES;
    [self.view addSubview:listTableView];
}
 
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
 
- (BOOL)shouldAutorotateToInterfaceOrientation:
    (UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 
- (void) setData:(int)num
{
    //데이타
    tableDataArray = [[NSMutableArray alloc]init];
    [tableDataArray addObject:[NSDictionary
        dictionaryWithObjectsAndKeys:
            @"미래를 꿈꾸는 기획자", @"subject", @"1", @"num", nil]];
             
    [tableDataArray addObject:
        [NSDictionary dictionaryWithObjectsAndKeys:
            @"꿈꾸는 아이폰 개발자", @"subject", @"2", @"num", nil]];
         
    [tableDataArray addObject:
        [NSDictionary dictionaryWithObjectsAndKeys:
            @"재미있는 디자이너의 꿈", @"subject", @"3", @"num", nil]];
 
    more = 0;
    if([tableDataArray count]>10){
        cellCount = 10+1;
        more = 1;//더보기 있을때
    }else{
        more = 0;//더보기 없을때
        cellCount = [tableDataArray count];
    }
}
 
#pragma tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}
 
- (NSInteger)tableView:(UITableView *)tableView
    numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    // return [tableDataArray count];
    return cellCount;
}
 
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
    cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    // UITableViewCell *cell =
        [[[UITableViewCell alloc]
            initWithStyle:UITableViewCellStyleSubtitle
            reuseIdentifier:CellIdentifier] autorelease];
 
    UITableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell =
            [[[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleSubtitle
                reuseIdentifier:CellIdentifier] autorelease];
    }
 
    // Configure the cell...
    NSDictionary *dic = [tableDataArray objectAtIndex:indexPath.row];
 
    CGRect frame = cell.textLabel.frame;
    frame.size.width = 320;
    cell.textLabel.frame = frame;
 
    //더 보기 그리기
    if (more==1 && indexPath.row+1 == cellCount) {
        cell.textLabel.text = @"더 보기";
    }
    //내용 그리기
    else
    {
        //텍스트
        cell.textLabel.text =
            [NSString stringWithFormat:@"%@",
                [dic objectForKey:@"subject"]];
        // [cell.textLabel setFont:[UIFont systemFontOfSize:14]];
    }
     
    return cell;
}
 
- (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //더보기 버튼 눌렀을때
    if(more == 1 && indexPath.row+1 == cellCount){
        NSLog(@"더보기 클릭");
 
        //마지막 페이지 인지 확인
        if (cellCount-1 < [tableDataArray count]) {
            if (([tableDataArray count] - cellCount) >= 10 ) {
                cellCount += 10;
            }else{
                cellCount += ([tableDataArray count] - cellCount);
                // cellCount --;
                more = 0;
            }
        }
         
        [listTableView reloadData];
    }
    //다음화면 넘기기
    //상세화면 들어가기
    else
    {
    }
 
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
 
// cell height
-(CGFloat) tableView:(UITableView *)tableView
    heightForRowAtIndexPath:(NSIndexPath *) indexPath
{
    return heightCell;
}


//동기식 (팜즈싱크에서 동기로 했을때)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
NSString *urlString =
    NSString stringWithFormat:
        encodedUrl2, encodedUrl37, encodedUrl11];
 
NSURL *nsurl =[NSURL URLWithString:urlString];
NSMutableURLRequest *request0 =
    [NSMutableURLRequest requestWithURL:nsurl
        cachePolicy:NSURLRequestUseProtocolCachePolicy
        timeoutInterval:60.0];
 
NSHTTPURLResponse *response;
NSError *error;
NSData *recive =
    [NSURLConnection
        sendSynchronousRequest:request0
        returningResponse:&response error:&error ];


//동기식 (간단한 다른 방법)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[NSString stringWithContentsOfURL:
    [NSURL URLWithString: stringEntryURL]
    encoding: 0x80000003 error: &error];
     
[NSString stringWithContentsOfURL:
    [NSURL URLWithString: stringEntryURL]
    encoding: CFStringConvertEncodingToNSStringEncoding(0x00000422)
    error: &error];
     
[NSString stringWithContentsOfURL:
    [NSURL URLWithString: stringEntryURL]
    encoding: 0x80000940
    error: &error];
 
[NSString stringWithContentsOfURL:
    [NSURL URLWithString: stringEntryURL]
    encoding: NSUTF8StringEncoding
    error: &error];