iphone开发随笔,有用的

 

 

1.将view设置成圆角
首先导入QuartzCore.framework,#import <QuartzCore/QuartzCore.h>
然后添加下面两行代码:
view.layer.cornerRadius = 8;//圆角
view.layer.masksToBounds = YES;//在所在的层绘制圆角
2.把UIColor转换为CGColor
UIColor *redColor = [UIColor redColor];
CGColor *RedColor = redColor.CGColor;
3.CALayer就是层,这个层你随便控制他的大小,旋转,角度,坐标变化或者内容之类的信息,这些变化还可以通过动画表现出来。UIView所有你 能看到的显示的内容,后面都有一个Layer。下面来自定义添加一个CALayer。
CALayer *layer = [[CALayer alloc] init];//定义一个layer
CGRect aa = CGRectMake(10, 30, 240, 240);//设置该layer的坐标和大小
layer.frame = aa;
UIColor *c = [UIColor redColor];
[layer setBackgroundColor:(c.CGColor)];//设置该layer的背景,因为layer setBackgroundColor用到的是CGColor所以要进行一次转换
[self.view.layer insertSublayer:layer atIndex:0];//在self view中添加该layer
4.从网络下载图片并显示
NSURL *url = [NSURL URLWithString:@"XXXX"];
NSData *picData = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:picData];
[imageView setImage:img];
5.Objective-C中切分数组
使用-componentsSeparatedByString:来切分NSArray。 如:
NSString *string = @”white:black:blue:red”;
NSArray *aArray = [string componentsSeparatedByString:@":"];
用-componentsJoinedByString:来合并NSArray中的各个元素并创建一个新的字符串,如:
string = [aArray componentsJoinedByString:@","];
这样,上面的数组就中的各个元素就以”,”分割形成一个字符串。
6.去除nsstring中的空格,table 以及newline,nextline
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *username = [mUsernameField stringValue];
username = [username stringByTrimmingCharactersInSet:whitespace];

7.如果在程序中想对某张图片进行处理的话(得到某张图片的一部分)可一用以下代码:

UIImage *image = [UIImageimageNamed:filename];
CGImageRef imageRef = image.CGImage;
CGRect rect = CGRectMake(origin.x, origin.y ,size.width, size.height);
CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
UIImage *imageRect = [[UIImagealloc] initWithCGImage:imageRefRect];
8.判断设备是iphone还是iphone4的代码:
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)

9.判断邮箱输入的是否正确
- (BOOL) validateEmail: (NSString *) candidate {
NSString*emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:candidate];
}
10.如何把当前的视图作为照片保存到相册中去
#import <QuartzCore/QuartzCore.h>
UIGraphicsBeginImageContext(currentView.bounds.size); //currentView当前的view
[currentView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
11.本地通知(类似于push通知)按home键到后台十秒后触发
UILocalNotification *notification=[[UILocalNotificationalloc] init];
if (notification!=nil) {
NSLog(@">> support local notification");
NSDate *now=[NSDatenew];
notification.fireDate=[now addTimeInterval:10];
notification.timeZone=[NSTimeZonedefaultTimeZone];
notification.alertBody=@"该去吃晚饭了!";
[[UIApplication sharedApplication].scheduleLocalNotification:notification];
}
12.捕获iphone通话事件
CTCallCenter *center = [[CTCallCenter alloc] init];
center.callEventHandler = ^(CTCall *call)
{
NSLog(@"call:%@", call.callState);
}
13.使UIimageView的图像旋转
float rotateAngle = M_PI;
CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);
imageView.transform = transform;
14.设置旋转的原点
#import <QuartzCore/QuartzCore.h>
UIImageView *imageView = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"bg.png"]];
imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);
15.实现自定义的状态栏(遮盖状态栏)
CGRect frame = {{0, 0}, {320, 20}};
UIWindow* wd = [[UIWindowalloc] initWithFrame:frame];
[wd setBackgroundColor:[UIColor clearColor]];
[wdsetWindowLevel:UIWindowLevelStatusBar];
frame = CGRectMake(100, 0, 30, 20);
UIImageView* img = [[UIImageViewalloc] 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];
16.在程序中实现电话的拨打
//添加电话图标按钮
UIButton *btnPhone = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
btnPhone.frame = CGRectMake(280,10,30,30);
UIImage *image = [UIImageimageNamed:@"phone.png"];     
[btnPhone setBackgroundImage:image forState:UIControlStateNormal];
//点击拨号按钮直接拨号
[btnPhone addTarget:self action:@selector(callAction:event:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentViewaddSubview: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 = [[NSStringalloc] initWithFormat:@"tel://%@",number]; //number为号码字符串     
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]];//拨号
}
17.更改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];
          }
    }
}
18.设置时区
NSTimeZone *defaultTimeZone = [NSTimeZonedefaultTimeZone];
NSTimeZone *tzGMT = [NSTimeZone timeZoneWithName:@"GMT"];
[NSTimeZone setDefaultTimeZone:tzGMT];
上面两个时区任意用一个。
19.Ipad隐藏键盘的同时触发方法
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
- (IBAction)keyboardWillHide:(NSNotification *)note
20.iPhone的图片调整,移动,旋转
iPhone使用触摸技术,通过手指可以对图片进行移动、放大缩小、旋转等,本文介绍该技术的实现。
首先在头文件中定义委托UIGestureRecognizerDelegate,进行手势识别的处理
@interface StampDetailViewController : UIViewController
然后在执行文件中添加处理函数
// adds a set of gesture recognizers to one of our piece subviews
- (void)addGestureRecognizersToPiece:(UIView *)piece
{
UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotatePiece:)];
[piece addGestureRecognizer:rotationGesture];
[rotationGesture release];
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scalePiece:)];
[pinchGesture setDelegate:self];
[piece addGestureRecognizer:pinchGesture];
[pinchGesture release];
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panPiece:)];
[panGesture setMaximumNumberOfTouches:2];
[panGesture setDelegate:self];
[piece addGestureRecognizer:panGesture];
[panGesture release];
}
// scale and rotation transforms are applied relative to the layer's anchor point
// this method moves a gesture recognizer's view's anchor point between the user's fingers
- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
UIView *piece = gestureRecognizer.view;
CGPoint locationInView = [gestureRecognizer locationInView:piece];
CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];
}
}
#pragma mark -
#pragma mark === Touch handling ===
#pragma mark
// shift the piece's center by the pan amount
// reset the gesture recognizer's translation to {0, 0} after applying so the next callback is a delta from the current position
- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
UIView *piece = [gestureRecognizer view];
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
CGPoint translation = [gestureRecognizer translationInView:[piece superview]];
[piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
[gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
}
}
// rotate the piece by the current rotation
// reset the gesture recognizer's rotation to 0 after applying so the next callback is a delta from the current rotation
- (void)rotatePiece:(UIRotationGestureRecognizer *)gestureRecognizer
{
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
[gestureRecognizer view].transform = CGAffineTransformRotate([[gestureRecognizer view] transform], [gestureRecognizer rotation]);
[gestureRecognizer setRotation:0];
}
}
// scale the piece by the current scale
// reset the gesture recognizer's rotation to 0 after applying so the next callback is a delta from the current scale
- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer
{
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
[gestureRecognizer view].transform = CGAffineTransformScale([[gestureRecognizer view] transform], [gestureRecognizer scale], [gestureRecognizer
scale]);
[gestureRecognizer setScale:1];
}
}
最后将此类手势处理函数与需要变化的图片视图联系起来
[self addGestureRecognizersToPiece:myImage];

 

 

你可能感兴趣的:(iPhone开发)