iOS 개발에서 자주 사용하는 코드 정리
22227 단어 ios
1. label 필렛 설정
// layer
label.layer.cornerRadias = ;
//
label.layer.masksToBounds = YES;
label.layer.clipsToBounds = YES;
2. 날짜 형식 설정
( , )
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
:yyyy-MM-dd hh(HH):mm:ss
formatter.dateFormat = @" HH:mm";
3. 프레임 애니메이션
//
self.imageview.animationImages = self.images;
//
self.imageview.animationDuration = 0.2;
// 0
self.imageview.animationRepeatCount = 0;
//
[self.imageview startAnimating];
4. 팝업 프롬프트
// UIAlertController *obj1
+ (instancetype)alertControllerWithTitle: message: preferredStyle: preferredStyle;
// UIAlertAction *obj2
+ (instancetype)actionWithTitle: style: handler:(void (^ __nullable)(UIAlertAction *action))handler;
//
[self presentViewController:obj1 animated: / completion:nil];
5.타이머
// :
1.
timerWithTimeInterval:( )ti invocation:( )invocation repeats:(BOOL)yesOrNo;
2.
timerWithTimeInterval:( )ti target:( )aTarget selector:(SEL )aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
1,2 - (void)fire ;
scheduledTimerWithTimeInterval:( )ti invocation:( )invocation repeats:(BOOL)yesOrNo;
scheduledTimerWithTimeInterval:( )ti target:( )aTarget selector:(SEL )aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
//
[self.scrollView setContentOffset:CGPointMake(x, y) animated:YES];
// :
- (void)invalidate;
6. 메일박스 형식이 정확한 코드인지 판단
//
-(BOOL)isValidateEmail:(NSString *)email
{
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];
return [emailTest evaluateWithObject:email];
}
7. 이미지 압축
:UIImage *yourImage= [self imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];
//
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);
// Tell the old image to draw in this newcontext, with the desired
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
8. 사용 가능한 사진 업로드 코드를 직접 테스트
- (IBAction)uploadButton:(id)sender {
UIImage *image = [UIImage imageNamed:@"1.jpg"]; //
NSData *imageData = UIImageJPEGRepresentation(image,0.5);//
NSLog(@" :%i",[imageData length]);
// post url
NSString *urlString = @"http://192.168.1.113:8090/text/UploadServlet";
//
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; [request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
//
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r
--%@\r
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition:form-data; name=\"userfile\"; filename=\"2.png\"\r
"] dataUsingEncoding:NSUTF8StringEncoding]]; //
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r
\r
"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r
--%@--\r
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
// NSLog(@"1-body:%@",body);
NSLog(@"2-request:%@",request);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"3- :%@",returnString);
9. 이미지 뷰에 그림 로드
UIImage *myImage = [UIImage imageNamed:@"1.jpg"];
[imageView setImage:myImage];
[self.view addSubview:imageView];
10. 갤러리 작업
// :
UIImagePickerControllerSourceTypesourceType=UIImagePickerControllerSourceTypeCamera;
if (![UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
}
UIImagePickerController * picker = [[UIImagePickerControlleralloc]init];
picker.delegate = self;
picker.allowsEditing=YES;
picker.sourceType=sourceType;
[self presentModalViewController:picker animated:YES];
// :
-(void)imagePickerController:(UIImagePickerController*)pickerdidFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissModalViewControllerAnimated:YES];
UIImage * image=[info objectForKey:UIImagePickerControllerEditedImage];
[self performSelector:@selector(selectPic:) withObject:imageafterDelay:0.1];
}
-(void)selectPic:(UIImage*)image
{
NSLog(@"image%@",image);
imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[self.viewaddSubview:imageView];
[self performSelectorInBackground:@selector(detect:) withObject:nil];
}
detect ,
// :
-(void)imagePickerControllerDIdCancel:(UIImagePickerController*)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
11. 다음 View로 건너뛰기
nextWebView = [[WEBViewController alloc] initWithNibName:@"WEBViewController" bundle:nil];
[self presentModalViewController:nextWebView animated:YES];
// UIBarButtonItem
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];
[self.navigationItem setRightBarButtonItem:rightButton];
navigationBar
self.navigationController.navigationBarHidden = YES;//
iOS UIlabel ( )
UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(10, 100, 300, 180)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 150)];
label.text = @"Hello world! Hello world!Hello world! Hello world! Hello world! Hello world! Hello world! Hello world!Hello world! Hello world! Hello world! Hello world! Hello world! Helloworld!";
//
label.backgroundColor = [UIColor redColor];
//
label.textColor = [UIColor whiteColor];
//
label.textAlignment = UITextAlignmentCenter;
//
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
12. 코드 생성 button
CGRect frame = CGRectMake(0, 400, 72.0, 37.0);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setTitle:@" " forState: UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
button.tag = 2000;
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
13. View의 중심에 컨트롤 표시
( , label,View)label.center = self.view.center;
14. 보기 좋은 문서 처리
tableView cell textLabel :
cell.backgroundColor = [UIColorscrollViewTexturedBackgroundColor];
//
cell.textLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:100.0f];
//
cell.textLabel.textColor = [UIColor orangeColor];
//
cell.textLabel.shadowColor = [UIColor whiteColor];
//
cell.textLabel.textAlignment = UITextAlignmentCenter;
15. Status Bar 숨기기
, viewDidLoad
[[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];
16. AlertView 배경 변경
UIAlertView *theAlert = [[[UIAlertViewalloc] initWithTitle:@"Atention"
message: @"I'm a Chinese!"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Okay",nil] autorelease];
[theAlert show];
UIImage *theImage = [UIImageimageNamed:@"loveChina.png"];
theImage = [theImage stretchableImageWithLeftCapWidth:0topCapHeight:0];
CGSize theSize = [theAlert frame].size;
UIGraphicsBeginImageContext(theSize);
[theImage drawInRect:CGRectMake(5, 5, theSize.width-10, theSize.height-20)];// , alertview 。
theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
theAlert.layer.contents = (id)[theImage CGImage];
17. 키보드 투명도
textField.keyboardAppearance = UIKeyboardAppearanceAlert;
[UIApplication sharedApplication].networkActivityIndicatorVisible, NO。
18. 화면 캡처
// CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400));
//renderInContext
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//
UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
//
UIGraphicsEndImageContext();
// png
imageData = UIImagePNGRepresentation(aImage);
19. 셀이 선택한 배경 변경
UIView *myview = [[UIView alloc] init]; myview.frame = CGRectMake(0, 0, 320, 47); myview.backgroundColor = [UIColorcolorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
cell.selectedBackgroundView = myview;
20. 이미지 표시
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect]; [myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES; //opaque
[self.view addSubview:myImage];
21. 그림이 상자의 크기에 맞게
NSString*imagePath = [[NSBundle mainBundle] pathForResource:@"XcodeCrash"ofType:@"png"];
UIImage *image = [[UIImage alloc]initWithContentsOfFile:imagePath];
UIImage *newImage= [image transformWidth:80.f height:240.f];
UIImageView *imageView = [[UIImageView alloc]initWithImage:newImage];
[newImagerelease];
[image release];
[self.view addSubview:imageView];
22. 그림을 클릭하여 이동하는 코드를 실현한다. 배경 그림이 있는 button을 생성하고 button에 클릭 이벤트를 추가한다.
UIButton *imgButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 120, 120)];
[imgButton setBackgroundImage:(UIImage *)[self.imgArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
imgButton.tag=[indexPath row];
[imgButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
최근에야 github에 뭘 넣기 시작했는데 회사에서는 못 넣는다고 썼어요.
github 주소:https://github.com/FuThD
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Swift의 패스트 패스Objective-C를 대체하기 위해 만들어졌지만 Xcode는 Objective-C 런타임 라이브러리를 사용하기 때문에 Swift와 함께 C, C++ 및 Objective-C를 컴파일할 수 있습니다. Xcode는 S...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.