您的位置:首页 > 编程语言

一些常用的代码片段,提高开发效率

2011-11-14 08:10 513 查看
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);

}

转自:http://blog.sina.com.cn/s/blog_6a2cbc930100m7eh.html

posted @ 2010-11-16 17:24 Sure-G 阅读(518) 评论(0) 编辑

iphone-常用的对视图图层(layer)的操作


iphone-常用的对视图图层(layer)的操作

对图层的操作:

1.给图层添加背景图片:

myView.layer.contents = (id)[UIImage imageNamed:@"view_BG.png"].CGImage;

2.将图层的边框设置为圆脚

myWebView.layer.cornerRadius = 8;

myWebView.layer.masksToBounds = YES;

3.给图层添加一个有色边框

myWebView.layer.borderWidth = 5;

myWebView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:1] CGColor];

转自:http://www.cnblogs.com/tracy-e/archive/2010/10/14/1851035.html

posted @ 2010-11-16 16:41 Sure-G 阅读(345) 评论(2) 编辑

iPhone中的剪切技巧

iPhone中的剪切技巧:

  
1.获取图形上下文

  
2.构造剪切的路径(形状)

  3.构建剪切区域

  
4.贴上你的画

// 1CGContextRef context = UIGraphicsGetCurrentContext();

// 2CGRect bounds = CGRectMake(0.0f, 0.0f, SIDELENGTH, SIDELENGTH);

CGMutablePathRef path = CGPathCreateMutable();CGPathAddEllipseInRect(path, NULL, bounds);

// 3CGContextAddPath(context, path);CGContextClip(context);

// 4[LOGO drawInRect:bounds];

截取屏幕图片

//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)

UIGraphicsBeginImageContext(CGSizeMake(200,400));

//renderInContext 呈现接受者及其子范围到指定的上下文

[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

//返回一个基于当前图形上下文的图片

UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();

//移除栈顶的基于当前位图的图形上下文

UIGraphicsEndImageContext();

//以png格式返回指定图片的数据

imageData = UIImagePNGRepresentation(aImage);

posted @ 2010-11-16 16:36 Sure-G 阅读(153) 评论(0) 编辑

iphone电话薄信息和用户设定的本机号码

//获取用户设置的本机号码(4.0以前的系统有效,4.0以后暂时没找到获取方法)

NSString *phoneNumber = [[NSUserDefaults standardUserDefaults] valueForKey:@"SBFormattedPhoneNumber"];

//iphone获取本机电话薄里的电话号码列表

/private/var/mobile/Library/AddressBook/AddressBook.sqlitedb

posted @ 2010-11-16 16:32 Sure-G 阅读(680) 评论(3) 编辑

自己新添加的一些NSDate的分类方法

////*****.m文件

#import "NSDate-Helper.h"

@implementation NSDate(Helpers)

/*

* This guy can be a little unreliable and produce unexpected results,

* you're better off using daysAgoAgainstMidnight

*/

//获取年月日如:19871127.

- (NSString *)getFormatYearMonthDay

{

NSString *string = [NSString stringWithFormat:@"%d%02d%02d",[self getYear],[self getMonth],[self getDay]];

return string;

}

//返回当前月一共有几周(可能为4,5,6)

- (int )getWeekNumOfMonth

{

return [[self endOfMonth] getWeekOfYear] - [[self beginningOfMonth] getWeekOfYear] + 1;

}

//该日期是该年的第几周

- (int )getWeekOfYear

{

int i;

int year = [self getYear];

NSDate *date = [self endOfWeek];

for (i = 1;[[date dateAfterDay:-7 * i] getYear] == year;i++)

{

}

return i;

}

//返回day天后的日期(若day为负数,则为|day|天前的日期)

- (NSDate *)dateAfterDay:(int)day

{

NSCalendar *calendar = [NSCalendar currentCalendar];

// Get the weekday component of the current date

// NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];

NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];

// to get the end of week for a particular date, add (7 - weekday) days

[componentsToAdd setDay:day];

NSDate *dateAfterDay = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];

[componentsToAdd release];

return dateAfterDay;

}

//month个月后的日期

- (NSDate *)dateafterMonth:(int)month

{

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];

[componentsToAdd setMonth:month];

NSDate *dateAfterMonth = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];

[componentsToAdd release];

return dateAfterMonth;

}

//获取日

- (NSUInteger)getDay{

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *dayComponents = [calendar components:(NSDayCalendarUnit) fromDate:self];

return [dayComponents day];

}

//获取月

- (NSUInteger)getMonth

{

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *dayComponents = [calendar components:(NSMonthCalendarUnit) fromDate:self];

return [dayComponents month];

}

//获取年

- (NSUInteger)getYear

{

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *dayComponents = [calendar components:(NSYearCalendarUnit) fromDate:self];

return [dayComponents year];

}

//获取小时

- (int )getHour {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit|NSMinuteCalendarUnit;

NSDateComponents *components = [calendar components:unitFlags fromDate:self];

NSInteger hour = [components hour];

return (int)hour;

}

//获取分钟

- (int)getMinute {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit|NSMinuteCalendarUnit;

NSDateComponents *components = [calendar components:unitFlags fromDate:self];

NSInteger minute = [components minute];

return (int)minute;

}

- (int )getHour:(NSDate *)date {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit|NSMinuteCalendarUnit;

NSDateComponents *components = [calendar components:unitFlags fromDate:date];

NSInteger hour = [components hour];

return (int)hour;

}

- (int)getMinute:(NSDate *)date {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit|NSMinuteCalendarUnit;

NSDateComponents *components = [calendar components:unitFlags fromDate:date];

NSInteger minute = [components minute];

return (int)minute;

}

//在当前日期前几天

- (NSUInteger)daysAgo {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *components = [calendar components:(NSDayCalendarUnit)

fromDate:self

toDate:[NSDate date]

options:0];

return [components day];

}

//午夜时间距今几天

- (NSUInteger)daysAgoAgainstMidnight {

// get a midnight version of ourself:

NSDateFormatter *mdf = [[NSDateFormatter alloc] init];

[mdf setDateFormat:@"yyyy-MM-dd"];

NSDate *midnight = [mdf dateFromString:[mdf stringFromDate:self]];

[mdf release];

return (int)[midnight timeIntervalSinceNow] / (60*60*24) *-1;

}

- (NSString *)stringDaysAgo {

return [self stringDaysAgoAgainstMidnight:YES];

}

- (NSString *)stringDaysAgoAgainstMidnight:(BOOL)flag {

NSUInteger daysAgo = (flag) ? [self daysAgoAgainstMidnight] : [self daysAgo];

NSString *text = nil;

switch (daysAgo) {

case 0:

text = @"Today";

break;

case 1:

text = @"Yesterday";

break;

default:

text = [NSString stringWithFormat:@"%d days ago", daysAgo];

}

return text;

}

/返回一周的第几天(周末为第一天)

- (NSUInteger)weekday {

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *weekdayComponents = [calendar components:(NSWeekdayCalendarUnit) fromDate:self];

return [weekdayComponents weekday];

}

//转为NSString类型的

+ (NSDate *)dateFromString:(NSString *)string {

return [NSDate dateFromString:string withFormat:[NSDate dbFormatString]];

}

+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format {

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];

[inputFormatter setDateFormat:format];

NSDate *date = [inputFormatter dateFromString:string];

[inputFormatter release];

return date;

}

+ (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format {

return [date stringWithFormat:format];

}

+ (NSString *)stringFromDate:(NSDate *)date {

return [date string];

}

+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed {

/*

* if the date is in today, display 12-hour time with meridian,

* if it is within the last 7 days, display weekday name (Friday)

* if within the calendar year, display as Jan 23

* else display as Nov 11, 2008

*/

NSDate *today = [NSDate date];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *offsetComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)

fromDate:today];

NSDate *midnight = [calendar dateFromComponents:offsetComponents];

NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];

NSString *displayString = nil;

// comparing against midnight

if ([date compare:midnight] == NSOrderedDescending) {

if (prefixed) {

[displayFormatter setDateFormat:@"'at' h:mm a"]; // at 11:30 am

} else {

[displayFormatter setDateFormat:@"h:mm a"]; // 11:30 am

}

} else {

// check if date is within last 7 days

NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];

[componentsToSubtract setDay:-7];

NSDate *lastweek = [calendar dateByAddingComponents:componentsToSubtract toDate:today options:0];

[componentsToSubtract release];

if ([date compare:lastweek] == NSOrderedDescending) {

[displayFormatter setDateFormat:@"EEEE"]; // Tuesday

} else {

// check if same calendar year

NSInteger thisYear = [offsetComponents year];

NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)

fromDate:date];

NSInteger thatYear = [dateComponents year];

if (thatYear >= thisYear) {

[displayFormatter setDateFormat:@"MMM d"];

} else {

[displayFormatter setDateFormat:@"MMM d, yyyy"];

}

}

if (prefixed) {

NSString *dateFormat = [displayFormatter dateFormat];

NSString *prefix = @"'on' ";

[displayFormatter setDateFormat:[prefix stringByAppendingString:dateFormat]];

}

}

// use display formatter to return formatted date string

displayString = [displayFormatter stringFromDate:date];

[displayFormatter release];

return displayString;

}

+ (NSString *)stringForDisplayFromDate:(NSDate *)date {

return [self stringForDisplayFromDate:date prefixed:NO];

}

- (NSString *)stringWithFormat:(NSString *)format {

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];

[outputFormatter setDateFormat:format];

NSString *timestamp_str = [outputFormatter stringFromDate:self];

[outputFormatter release];

return timestamp_str;

}

- (NSString *)string {

return [self stringWithFormat:[NSDate dbFormatString]];

}

- (NSString *)stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle {

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];

[outputFormatter setDateStyle:dateStyle];

[outputFormatter setTimeStyle:timeStyle];

NSString *outputString = [outputFormatter stringFromDate:self];

[outputFormatter release];

return outputString;

}

//返回周日的的开始时间

- (NSDate *)beginningOfWeek {

// largely borrowed from "Date and Time Programming Guide for Cocoa"

// we'll use the default calendar and hope for the best

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDate *beginningOfWeek = nil;

BOOL ok = [calendar rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek

interval:NULL forDate:self];

if (ok) {

return beginningOfWeek;

}

// couldn't calc via range, so try to grab Sunday, assuming gregorian style

// Get the weekday component of the current date

NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];

/*

Create a date components to represent the number of days to subtract from the current date.

The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today's Sunday, subtract 0 days.)

*/

NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];

[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];

beginningOfWeek = nil;

beginningOfWeek = [calendar dateByAddingComponents:componentsToSubtract toDate:self options:0];

[componentsToSubtract release];

//normalize to midnight, extract the year, month, and day components and create a new date from those components.

NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)

fromDate:beginningOfWeek];

return [calendar dateFromComponents:components];

}

//返回当前天的年月日.

- (NSDate *)beginningOfDay {

NSCalendar *calendar = [NSCalendar currentCalendar];

// Get the weekday component of the current date

NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)

fromDate:self];

return [calendar dateFromComponents:components];

}

//返回该月的第一天

- (NSDate *)beginningOfMonth

{

return [self dateAfterDay:-[self getDay] + 1];

}

//该月的最后一天

- (NSDate *)endOfMonth

{

return [[[self beginningOfMonth] dateafterMonth:1] dateAfterDay:-1];

}

//返回当前周的周末

- (NSDate *)endOfWeek {

NSCalendar *calendar = [NSCalendar currentCalendar];

// Get the weekday component of the current date

NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];

NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];

// to get the end of week for a particular date, add (7 - weekday) days

[componentsToAdd setDay:(7 - [weekdayComponents weekday])];

NSDate *endOfWeek = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];

[componentsToAdd release];

return endOfWeek;

}

+ (NSString *)dateFormatString {

return @"yyyy-MM-dd";

}

+ (NSString *)timeFormatString {

return @"HH:mm:ss";

}

+ (NSString *)timestampFormatString {

return @"yyyy-MM-dd HH:mm:ss";

}

// preserving for compatibility

+ (NSString *)dbFormatString {

return [NSDate timestampFormatString];

}

@end

posted @ 2010-11-16 16:22 Sure-G 阅读(1260) 评论(0) 编辑

对数组进行排序(不写compare:方法)

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {

if ([obj1 integerValue] > [obj2 integerValue]) {

return (NSComparisonResult)NSOrderedDescending;

}

if ([obj1 integerValue] < [obj2 integerValue]) {

return (NSComparisonResult)NSOrderedAscending;

}

return (NSComparisonResult)NSOrderedSame;

}];

以前只用过[array sortedArrayUsingSelector:@selector(compare:)];方法,若没有现成的compare:方法还要自己写一个新的比较方法,比较麻烦.

在研究对数组逆向排序时看到了这个方法,貌似是4.0新出的blocks.(Block, 简单的说,就是一个函数对象,和其它类型的对象一样,你可以创建它,可以赋给一个变量,也可以作为函数的参数来传递)

blocks传送门:http://www.cocoachina.com/macdev/objc/2010/0601/1591.html

用法:若sortedArray存的数据是Person类的对象,(name,age,address...),要以age排序,即将上面方法中的[obj1 intergerValue] 改为[obj1/2 age]即可;或 要倒序排列,则将NSOrderedDescending和NSOrderedAscending调换.

转自:http://www.cnblogs.com/gushuo/archive/2010/11/16.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: