您的位置:首页 > 移动开发 > IOS开发

iOS学习笔记总结二(持续更新)

2014-05-13 17:15 691 查看

部分内容转自:/article/1409129.html

1.判断邮箱格式是否正确的代码

//利用正则表达式验证
-(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];
}


2.图片压缩

用法: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;
}


3.图片上传代码

- (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\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition:form-data; name=\"userfile\"; filename=\"2.png\"\r\n"] 	dataUsingEncoding:NSUTF8StringEncoding]]; //上传上去的图片名字
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",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);
}


4.隐藏Status Bar

读者可能知道一个简易的方法,那就是在程序的viewDidLoad中加入

[[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];

5.更改AlertView背景

UIAlertView *theAlert = [[UIAlertView alloc] initWithTitle:@"Atention"
message: @"I'm a Chinese!"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Okay",nil];
[theAlert show];
UIImage *theImage = [UIImage imageNamed:@"loveChina.png"];
theImage = [theImage stretchableImageWithLeftCapWidth:0 topCapHeight: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];


6.键盘透明

textField.keyboardAppearance = UIKeyboardAppearanceAlert;

7.状态栏的网络活动风火轮是否旋转

[UIApplication sharedApplication].networkActivityIndicatorVisible,默认值是NO。

8.当使用UITableView 的Plain风格时,cell的数量占不满一屏时,会出现无用的cell分割线,如何去掉

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
return [UIView new];

// If you are not using ARC:
// return [[UIView new] autorelease];
}


9.如何获取iOS 的idfa和mac地址

//for mac
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

//for idfa
#import <AdSupport/AdSupport.h>

- (NSString * )macString{

int                 mib[6];
size_t              len;
char                *buf;
unsigned char       *ptr;
struct if_msghdr    *ifm;
struct sockaddr_dl  *sdl;

mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;

if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error\n");
return NULL;
}

if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1\n");
return NULL;
}

if ((buf = malloc(len)) == NULL) {
printf("Could not allocate memory. error!\n");
return NULL;
}

if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2");
free(buf);
return NULL;
}

ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned charchar *)LLADDR(sdl);
NSString *macString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
free(buf);

return macString;
}

- (NSString *)idfaString {

NSBundle *adSupportBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/AdSupport.framework"];
[adSupportBundle load];

if (adSupportBundle == nil) {
return @"";
}
else{

Class asIdentifierMClass = NSClassFromString(@"ASIdentifierManager");

if(asIdentifierMClass == nil){
return @"";
}
else{

//for no arc
//ASIdentifierManager *asIM = [[[asIdentifierMClass alloc] init] autorelease];
//for arc
ASIdentifierManager *asIM = [[asIdentifierMClass alloc] init];

if (asIM == nil) {
return @"";
}
else{

if(asIM.advertisingTrackingEnabled){
return [asIM.advertisingIdentifier UUIDString];
}
else{
return [asIM.advertisingIdentifier UUIDString];
}
}
}
}
}

- (NSString *)idfvString
{
if([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) {
return [[UIDevice currentDevice].identifierForVendor UUIDString];
}

return @"";
}


不过请注意:iOS7之后,mac地址就获取不到了。参考(转):

In iOS7 and later,if you askfor
the MAC address of an iOS device, the system returns the value02:00:00:00:00:00.
If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifierfor their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager
instead.)
翻译:从iOS7及更高版本往后,如果你向ios设备请求获取mac地址,系统将返回一个固定值“02:00:00:00:00:00”,如果你需要识别设备的
唯一性,请使用UIDevice的identifierForVendor属性。(因广告目的而需要识别设备的应用,请考虑使用 ASIdentifierManager的advertisingIdentifier属性作为替代)

10.让TableViewCell中UITextFiled随点击滚动到可视位置(避免UITextFiled在TableView中被遮挡)

//textfile uitableview滚动
UITableViewCell *cell;
if (!IS_OS_7_OR_LATER) {
// Load resources for iOS 6.1 or earlier
cell = (UITableViewCell *) textField.superview.superview;

} else {
// Load resources for iOS 7 or later
cell = (UITableViewCell *) textField.superview.superview.superview;
// TextField -> UITableVieCellContentView -> (in iOS 7!)ScrollView -> Cell!
}


11.让UITableView的Cell不重用

有时候我们的UITableview的cell是有限的10个8个的,根本没必要重用。重用反而导致很多问题。其中思路就是,给这有限的10个cell不同的标示

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", [indexPath section], [indexPath row]];//以indexPath来唯一确定cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
}


12.在iOS 7,如何检测到系统自带ViewController手势返回结束

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
id<UIViewControllerTransitionCoordinator> tc = navigationController.topViewController.transitionCoordinator;
[tc notifyWhenInteractionEndsUsingBlock:^(id<UIViewControllerTransitionCoordinatorContext> context) {
NSLog(@"7: %i", [context isCancelled]);
}];
}


这个检测需要设置 self.navigationController.delegate = self;
当前viewController要UINavigationBarDelegate实现此协议。

还有一个关键的设置,需要在当前ViewController适当的地方设置self.navigationController.delegate = nil; 否则会导致崩溃。我是这样设置的,

在viewDidAppear设置self.navigationController.delegate = self; viewWillDisappear时设置self.navigationController.delegate =
nil;

保证设置成双成对。

参考:http://stackoverflow.com/questions/20639006/getting-interactivepopgesturerecognizer-dismiss-callback-event

13.如何设置Plain 风格下UITableView的Section的HeaderView不在UITableview上浮动

CGFloat dummyViewHeight = 40;
UIView *dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, dummyViewHeight)];
self.tableView.tableHeaderView = dummyView;
self.tableView.contentInset = UIEdgeInsetsMake(-dummyViewHeight, 0, 0, 0);
上面dummyViewHeight的值根据自己headerView的高度变化。就是你headerView的高度。

14、在程序中播放声音

首先在程序添加AudioToolbox.framework,其次,在有播放声音方法的.m方法添加#import<AudioToolbox/AudioToolbox.h>.播放声音的代码如下:

NSString *path = [[NSBundle mainBundle] pathForResource:@"soundFileName" ofType:@"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID ((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound (soundID);


15、让某一方法在未来某段时间之后执行

[self performSelector:@selector(方法名) withObject:nil afterDelay:延迟时间(s)];


16、获得设备版本号:

float version = [[[UIDevice currentDevice] systemVersion] floatValue];


17、捕捉程序关闭或者进入后台事件:

UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
applicationWillResignActive:这个方法中添加想要的操作

18、查看设备支持的字体:

for (NSString *family in [UIFont familyNames]) {
NSLog(@"%@", family);
for (NSString *font in [UIFont fontNamesForFamilyName:family]) {
NSLog(@"\t%@", font);
}
}


19、为UIImageView添加单击事件

imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(yourHandlingCode:)];
[imageView addGestureRecognizer:singleTap];

20、使程序支持iTunes这样的设备,比如可以使用PC端的工具往程序的Documents中拖放文件



21、页面切换效果设置

controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:controller animated:YES];
//可供使用的效果:

UIModalTransitionStyleCoverVertical  新视图从下向上出现
UIModalTransitionStyleFlipHorizontal 以设备的长轴为中心翻转出现
UIModalTransitionStyleCrossDissolve  渐渐显示
UIModalTransitionStylePartialCurl    原视图向上卷起
//恢复之前的页面:

[self dismissModalViewControllerAnimated:YES];


22、获取截屏

- (UIImage *)getScreenShot {
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}


23、深浅拷贝

系统的非容器类对象 (NSString,NSNumber等):如果对一不可变对象复制,copy是指针复制(浅拷贝)和mutableCopy就是对象复制(深拷贝)。如果是对可变对象复制,都是深拷贝,但是copy返回的对象是不可变的

系统的容器类对象(NSArray,NSDictionary等):对于容器而言,其元素对象始终是指针复制。如果需要元素对象也是对象复制,就需要实现深拷贝
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: