iPhone開發小技巧

來源:互聯網
上載者:User

1、如果在程式中想對某張圖片進行處理的話(得到某張圖片的一部分)可一用以下代碼:

UIImage *image = [UIImage imageNamed:filename];

CGImageRef imageRef = image.CGImage;

CGRect rect = CGRectMake(origin.x, origin.y ,size.width, size.height);

CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);

UIImage *imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];

 

2、判斷裝置是iphone還是iphone4的代碼:


#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)


3、判斷郵箱輸入的是否正確:


- (BOOL) validateEmail: (NSString *) candidate {

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:candidate];

}

 

4、如何把當前的視圖作為照片儲存到相簿中去:

 

#import <QuartzCore/QuartzCore.h>

UIGraphicsBeginImageContext(currentView.bounds.size);     //currentView 當前的view

[currentView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

 

5、本地通知(類似於push通知)按home鍵到後台 十秒後觸發:

UILocalNotification *notification=[[UILocalNotification alloc] init];

if (notification!=nil) {

NSLog(@">> support local notification");

NSDate *now=[NSDate new];

notification.fireDate=[now addTimeInterval:10];

notification.timeZone=[NSTimeZone defaultTimeZone];

notification.alertBody=@"該去吃晚飯了!";

[[UIApplication sharedApplication].scheduleLocalNotification:notification];

}

 

6、捕獲iphone通話事件:

CTCallCenter *center = [[CTCallCenter alloc] init];

center.callEventHandler = ^(CTCall *call)

{

NSLog(@"call:%@", call.callState);

}

 

7、iOS 4 引入了多任務支援,所以使用者按下 “Home” 鍵以後程式可能並沒有退出而是轉入了後台運行。如果您想讓應用直接退出,最簡單的方法是:在 info-plist 裡面找到 Application does not run in background 一項,勾選即可。


8、使UIimageView的映像旋轉:


float rotateAngle = M_PI;

CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);

imageView.transform = transform;

 

9、設定旋轉的原點:

 

#import <QuartzCore/QuartzCore.h>

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg.png"]];

imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);

 

10、實現自訂的狀態列(遮蓋狀態列):

CGRect frame = {{0, 0}, {320, 20}};

UIWindow* wd = [[UIWindow alloc] initWithFrame:frame];

[wd setBackgroundColor:[UIColor clearColor]];

[wd setWindowLevel:UIWindowLevelStatusBar];

frame = CGRectMake(100, 0, 30, 20);

UIImageView* img = [[UIImageView alloc] initWithFrame:frame];

[img setContentMode:UIViewContentModeCenter];

[img setImage:[UIImage imageNamed:@"00_0103.png"]];

[wd addSubview:img];

[wd makeKeyAndVisible];

 

[UIView beginAnimations:nil context:nil];

[UIView setAnimationDuration:2];

frame.origin.x += 150;

[img setFrame:frame];

[UIView commitAnimations];


11、在程式中實現電話的撥打:


//添加電話表徵圖按鈕

UIButton *btnPhone = [[UIButton buttonWithType:UIButtonTypeCustom] retain];

btnPhone.frame = CGRectMake(280,10,30,30);

UIImage *image = [UIImage imageNamed:@"phone.png"];    

[btnPhone setBackgroundImage:image forState:UIControlStateNormal];

 

//點擊撥號按鈕直接撥號

[btnPhone addTarget:self action:@selector(callAction:event:)forControlEvents:UIControlEventTouchUpInside];

 

[cell.contentView addSubview:btnPhone];  //cell是一個UITableViewCell

 

//定義點擊撥號按鈕時的操作

- (void)callAction:(id)sender event:(id)event{

NSSet *touches = [event allTouches];

UITouch *touch = [touches anyObject];

CGPoint currentTouchPosition = [touch locationInView:self.listTable];

NSIndexPath *indexPath = [self.listTable indexPathForRowAtPoint: currentTouchPosition];

if (indexPath == nil) {

return;

}

NSInteger section = [indexPath section];

NSUInteger row = [indexPath row];

NSDictionary *rowData = [datas objectAtIndex:row];

 

NSString *num = [[NSString alloc] initWithFormat:@"tel://%@",number]; //number為號碼字串    

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]]; //撥號

}


12、更改iphone的鍵盤顏色:


1.只有這2種數字鍵台才有效果。UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad

2. keyboardAppearance = UIKeyboardAppearanceAlert

- (void)textViewDidBeginEditing:(UITextView *)textView{

NSArray *ws = [[UIApplication sharedApplication] windows];

for(UIView *w in ws){

NSArray *vs = [w subviews];

for(UIView *v in vs)

{

if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIKeyboard"])

{

v.backgroundColor = [UIColor redColor];

}

}

}

 

13、設定時區

 


NSTimeZone *defaultTimeZone = [NSTimeZone defaultTimeZone];

NSTimeZone *tzGMT = [NSTimeZone timeZoneWithName:@"GMT"];

[NSTimeZone setDefaultTimeZone:tzGMT];

上面兩個時區任意用一個。


14、Ipad隱藏鍵盤的同時觸發方法。

 

 

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(keyboardWillHide:)

name:UIKeyboardWillHideNotification

  object:nil];

 

- (IBAction)keyboardWillHide:(NSNotification *)note

 

14、在一個程式中開啟另一個程式的方法。

 

http://www.cocoachina.com/iphonedev/sdk/2010/0322/768.html

15、計算字串的字數

-(int)calculateTextNumber:(NSString *)text

{

float number = 0.0;

int index = 0;

for (index; index < [text length]; index++)

{

NSString *protoText = [text substringToIndex:[text length] - index];

NSString *toChangetext = [text substringToIndex:[text length] -1 -index];

NSString *charater;

if ([toChangetext length]==0)

{

charater = protoText;

}

else

{

NSRange range = [text rangeOfString:toChangetext];

charater = [protoText stringByReplacingCharactersInRange:range withString:@""];

 

}

NSLog(charater);

if ([charater lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 3)

{

number++;

}

else

{

number = number+0.5;

}

}

return ceil(number);
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.