热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

iPhone较为基础的代码片段

Iphone代码片段导航1.给UITableViewController添加ToolBar。self.navigationController.toolbarHiddenNO;默认

Iphone代码片段导航

1.给UITableViewController添加ToolBar。

 self.navigationController.toolbarHidden = NO; //默认是隐藏的。

//添加MessageToolBar ,messageToolBar是IBOutlet的一个ToolBar。

 self.toolbarItems =  [[[NSMutableArray alloc] initWithArray:self.messageToolBar.items] autorelease];

 self.navigationController.toolbar.barStyle = self.messageToolBar.barStyle; 

2.后台运行一个方法,如果该方法需要修改UI,为了防止出错,应在主线程里修改UI。

[self performSelectorInBackground:@selector(updateInfo)];

在UpdateInfo里如果要修改UI ,

[self performSelectorOnMainThread:@selector(updateUIMethod) withObject:nil waitUntilDone:NO];

同时注意,后台程序的方法应该放在NSAutoRelease pool里的,如下所示:

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
xxxx
[pool release];

3.在A类里动态的设定B类或者C类的方法。

[self.actionTarget performSelector:self.actionMethod withObject:parameter];

actionTarget   -> id类型的属性。设置B 类或者C类。

actionMethod -> Sel类型的属性。设置具体的方法名

parameter     -> 参数

4.设置Navigation的提示信息和进度条设置

   self.navigationItem.prompt : 提示信息
   self.navigationItem.titleView :存放ProgressBar等其它提示信息的View

   在进度条显示完了后,需要清空显示进度信息:

   self.navigationItem.prompt = nil;
   self.navigationItem.titleView = nil;

5.从资源文件xib里加载View的方法

 NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyView"
                                                         owner:self
                                                       options:nil];
MyView *view = [nib objectAtIndex:0];

6. UIAlterView 修改默认的Frame高度

在其委托里实现这个方法

-(void)willPresentAlertView:(UIAlertView*)alertView
{
alertView
.frame =CGRectMake(5.f,1.f,100.f,200.f);
}

参考:http://stackoverflow.com/questions/2763713/change-width-of-uialertview-in-ipad
 

 7.获取iphone屏幕大小

CGRect screenBounds = [ [ UIScreen mainScreen ] bounds ];
CGRect screenRect= [ [ UIScreen mainScreen ] applicationframe ]; 

8. 修改TableView的样式,让UITableView显示Windows的背景图片。

    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;

   如果要修改UITableCell的事情backgroundColor需要再 tableView:willDisplayCell:forRowAtIndexPath:里修改。

9.通过图片获取颜色。 

[UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName"]];

修改分割线颜色

 self.tableView.separatorColor = [UIColor blackColor]; 

显示文本的地方设置透明色 

 cell.textLabel.opaque = NO;

 这样整个cell就有立体感。 

10.设置UITableView 的checkmark显示样式

修改cell的 accessoryView 

 cell.accessoryView = UIImageView

11. 修改TableView距离导航缆的高度。 

 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{
return 10.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
return [[[UIView alloc] initWithFrame:CGRectZero] autorelease];;
}

12. 自定义TableViewCell的背景颜色和选择后的颜色。

 方法一:将TableViewCell的backgroundView和SelectBackGroundView修改成指定的View就可以了。

 方法二: 在Interface Builder里设置cell的image和SelectImage属性,但是要记得UItableView修改seperator的属性为None

13 颜色定义。

  美工一般定义好颜色,然后让程序员去填充颜色,美工一般给的是RGB颜色,那么RGB颜色如果换成UIColor

[UIColor colorWithRed:31.0/255 green:204.0/255 blue:39.0/255 alpha:1.0];

Red,Green,Blue只接受0-1的参数,换算方法是除以255。 

14. Xcode 4设置  NSZombieEnabled

 if you click on the scheme drop down bar -> edit scheme -> arguments tab and then add NSZombieEnabled in the Environment Variables column and YES in the value column

15.自动生成多语言化的StringTable

   如果在代码里全部是通过 NSLocalizedString(@"中文", nil)来对应多语言,最后要整理一个list,手动一个一个粘贴太麻烦。

  自动化生成方法:在命令行目录下进入项目根目录:执行 genstrings -a $(find . -name "*.m"),就会自动生成一个文件对应。

  参考网址 http://steelwheels.sourceforge.jp/Documents/genstring.html

http://iphone.longearth.net/2009/05/25/%E3%80%90iphone%E3%80%91localizablestrings%E3%82%92%E8%87%AA%E5%8B%95%E3%81%A7%E4%BD%9C%E3%82%8B-genstrings/ 

16.自定义bond字体 

[UIFont fontWithName:@"Helvetica-Bold" size:16.0] 

17  无边框透明UITableViewCell

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;   

self.tableView.separatorColor = [UIColor clearColor];              

self.tableView.backgroundColor = [UIColor clearColor];   

self.tableView.opaque = NO;   

self.tableView.backgroundView = nil;

--Cell修改--

self.backgroundView = [[[UIView alloc] init] autorelease];       

self.backgroundView.backgroundColor = [UIColor clearColor];       

self.selectedBackgroundView = [[[UIView alloc] init] autorelease];       

self.selectedBackgroundView.backgroundColor = [UIColor clearColor];

18. 隐藏Tabbar

SampleViewController*obj =[[SampleViewController alloc] init];
[obj setHidesBottomBarWhenPushed:YES];
[self.navigationController pushViewController:obj animated:YES];
[obj release];

19.从UIView获取UImage

#import QuartzCore/QuartzCore.h

- (UIImage *)getImageFromView:(UIView *)orgView  

{ UIGraphicsBeginImageContext(orgView.bounds.size);  

[orgView.layer renderInContext:UIGraphicsGetCurrentContext()];  

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();  

UIGraphicsEndImageContext();  

return image;  

20. 添加手式识别后,会屏蔽掉touchend方法

 

21.获取手机号码,和IMEI  

 

获取本地iphone手机号码

[[NSUserDefaults standardUserDefaults] valueForKey:@"SBFormattedPhoneNumber"];  

获取手机的imei

#import "Message/NetworkController.h" 

NetworkController *ntc=[[NetworkController sharedInstance] autorelease];  

NSString *imeistring = [ntc IMEI];  

imeistring就是获取的imei。 IMEI(International Mobile Equipment Identity)是国际移动设备身份码的缩写,国际移动装备辨识码,是由15位数字组成的"电子串号",它与每台手机一一对应,而且该码是全世界唯一的。

22 NLog的格式,经常忘记,做个笔记

%@ 对象
%d, %i 整数
%u   无符整形
%f 浮点/双字
%x, %X 二进制整数
%o 八进制整数
%zu size_t
%p 指针
%e   浮点/双字 (科学计算)
%g   浮点/双字
%s C 字符串
%.*s Pascal字符串
%c 字符
%C unichar
%lld 64位长整数(long long)
%llu   无符64位长整数
%Lf 64位双字

23.更改UISearchBar最下面黑色的边框

 #define SEARCHBAR_BORDER_TAG 1337

- (void) viewDidLoad{
// Set a custom border on the bottom of the search bar, so it's not so harsh
UISearchBar *searchBar = self.searchDisplayController.searchBar;
UIView *bottomBorder = [[UIView alloc] initWithFrame:CGRectMake(0,searchBar.frame.size.height-1,searchBar.frame.size.width, 1)];
[bottomBorder setBackgroundColor:[UIColor colorWithWhite:200.0f/255.f alpha:1.0f]];
[bottomBorder setOpaque:YES];
[bottomBorder setTag:SEARCHBAR_BORDER_TAG];
[searchBar addSubview:bottomBorder];
[bottomBorder release];
}

 

24.设置键盘的默认形式。

   比如UITextField 设置为默认数字,和只允许数组数字

   //默认数字 

   textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation
   //只允许输入数字   

   textField.keyboardType = UIKeyboardTypeNumberPad

 

25.UIButton设置文字左对齐

- emailBtn.contentHorizontalAlignment = UIontrolContentHorizontalAlignmentLeft;
- emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
- CGRect buttonRect = emailBtn.bounds;  
UILabel *myLabel = [[UILabel alloc] initWithFrame: buttonRect];
myLabel = UITextAlignmentLeft;
[emailBtn addSubview:myLabel];

   [myLabel release];  

26. retain异常的时候重载这个方法设置断点查看和分析

- (id) retain

{
// Break here to see who is retaining me.
return [super retain];
}

 

27.去掉白色半圆

Plist添加 

 Icon already includes gloss effects 为YES

 

UIPrerenderedIcon 设置不起作用(Xcode4 .0.2)


28.tableView reloadRowsAtIndexPaths 如果不在可见区域,将不会重新加载。  

29. 设置应用程序的statusbaryanse

再plist里设置Status bar style  Opaque black style

 

30. 设置控件的copy paste的本地化

   - 设置Localization native development region   =》 china

   - 将项目的en.lproj 改成zh_CN.lproj

 31. 允许应用程序通过itunes上传文件(ios3.2以上)

 在info.plist里设置 UIFileSharingEnabled  => YES

 32. 获取UICOLOR的rgb值

const CGFloat* components = CGColorGetComponents(SelectedColor.CGColor);
NSLog(@"Red: %f", components[0]);
NSLog(@"Green: %f", components[1]); 
NSLog(@"Blue: %f", components[2]);

NSLog(@"Alpha: %f", CGColorGetAlpha(SelectedColor.CGColor)); 

 

33.获取2个时间之间的天,小时,分钟

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

NSTimeInterval interval = [date timeIntervalSinceNow];
NSString * timeRemaining = nil;
if (interval > 0) {
div_t d = div(interval, 86400);
int day = d.quot;
div_t h = div(d.rem, 3600);
int hour = h.quot;
div_t m = div(h.rem, 60);
int min = m.quot;
NSString * nbday = nil;
if(day > 1)
nbday = @"days";
else if(day == 1)
nbday = @"day";
else
nbday = @"";
NSString * nbhour = nil;
if(hour > 1)
nbhour = @"hours";
else if (hour == 1)
nbhour = @"hour";
else
nbhour = @"";
NSString * nbmin = nil;
if(min > 1)
nbmin = @"mins";
else
nbmin = @"min";
timeRemaining = [NSString stringWithFormat:@"%@%@ %@%@ %@%@",day ? [NSNumber numberWithInt:day] : @"",nbday,hour ? [NSNumber numberWithInt:hour] : @"",nbhour,min ? [NSNumber numberWithInt:min] : @"00",nbmin];
}
else
timeRemaining = @"Over";
return timeRemaining;
}

 

34. Icon specified in the Info.plist not found under the top level app wrapper 

     记住Icon 首字母是大写的,不是icon.png , 是Icon.png 

 

35. 

[iphone]Code Sign error: Provisioning profile XXXX can't be found

http://www.cnblogs.com/baryon/archive/2010/05/06/1728968.html 

http://www.douban.com/note/131009422/ 

 

1.关闭你的项目,找到项目文件XXXX.xcodeproj,在文件上点击右键,选择“显示包内容”(Show Package Contents)。会新打开一个Finder。注:其实XXXX.xcodeproj就是一个文件夹,这里新打开的一个Finder里面的三个文件就是该XXXX.xcodeproj文件夹里面的文件。
2.在新打开的Finder中找到project.pbxproj,并且打开。在这之中找到你之前的证书的编码信息。我之前报的错误信息是
Code Sign error: Provisioning profile '37D44E7F-0339-4277-9A82-C146A944CD46',所以我用查找的方式找到了所有包括37D44E7F-0339-4277-9A82-C146A944CD46的行,并且删除。
3.保存,重新启动你的项目,再编译。就OK了。

 

 36.获取手机唯一ID

UIDevice *device = [UIDevice currentDevice];//创建设备对象
NSString *deviceUID = [[NSString alloc] initWithString:[device uniqueIdentifier]];

NSLog(@"%@",deviceUID); // 输出设备id 

 

37 .动态调用一个类的方法

 View Code

 

 

 38.改变NavigationViewController默认动画,让其旋转

navigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; 

 

39 .显示和隐藏StatsBar

  [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone]; 

  启动隐藏StatusBar  info.plist  添加 Status bar is initially hidden  为bool Yes

40 . 点击某个cell的按钮,收藏到tabbar里  

http://stackoverflow.com/questions/5926554/get-uitableviewcell-position-from-visible-area-or-window

41. CoreText用文字填充不规则图形

  CGContextRef context = UIGraphicsGetCurrentContext();

    //Flip the coordinate system
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    //Create a path to render text in
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.bounds );
    
    //An attributed string containing the text to render
    NSAttributedString* attString = [[NSAttributedString alloc]
                                      initWithString:...];
    
    //Create a path to wrap around
    CGMutablePathRef clipPath = CGPathCreateMutable();
    CGPathAddEllipseInRect(clipPath, NULL, CGRectMake(200, 200, 300, 300) );

    //A CFDictionary containing the clipping path
    CFStringRef keys[] = { kCTFramePathClippingPathAttributeName };
    CFTypeRef values[] = { clipPath };
    CFDictionaryRef clippingPathDict = CFDictionaryCreate(NULL, 
             (const void **)&keys, (const void **)&values,
              sizeof(keys) / sizeof(keys[0]), 
              &kCFTypeDictionaryKeyCallBacks, 
              &kCFTypeDictionaryValueCallBacks);

    //An array of clipping paths -- you can use more than one if needed!
    NSArray *clippingPaths = [NSArray arrayWithObject:(NSDictionary*)clippingPathDict];
    
    //Create an options dictionary, to pass in to CTFramesetter
    NSDictionary *optionsDict = [NSDictionary dictionaryWithObject:clippingPaths forKey:(NSString*)kCTFrameClippingPathsAttributeName];

    //Finally create the framesetter and render text
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString); //3
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter,
                             CFRangeMake(0, [attString length]), path, optionsDict);
    
    CTFrameDraw(frame, context);
    
    //Clean up
    CFRelease(frame);
    CFRelease(path);

    CFRelease(framesetter); 

 http://amyworrall.com/post/11098565269/text-wrap-with-core-text

42 . Animation开始和结束callback

     UIView 

      - (void)animateStuff {

[UIView beginAnimations:@"animationName" context:nil];
[UIView setAnimationDelegate:self];
    [self.view doWhatever];
    [UIView commitAnimations];
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    if ([finished boolValue]) {
        NSLog(@"Animation Done!");
    }

 

  CoreAnimation

   CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];

anim.delegate = self;
     
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
 {

 




推荐阅读
  • 使用圣杯布局模式实现网站首页的内容布局
    本文介绍了使用圣杯布局模式实现网站首页的内容布局的方法,包括HTML部分代码和实例。同时还提供了公司新闻、最新产品、关于我们、联系我们等页面的布局示例。商品展示区包括了车里子和农家生态土鸡蛋等产品的价格信息。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • 本文介绍了PE文件结构中的导出表的解析方法,包括获取区段头表、遍历查找所在的区段等步骤。通过该方法可以准确地解析PE文件中的导出表信息。 ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • ScrollView嵌套Collectionview无痕衔接四向滚动,支持自定义TitleView
    本文介绍了如何实现ScrollView嵌套Collectionview无痕衔接四向滚动,并支持自定义TitleView。通过使用MainScrollView作为最底层,headView作为上部分,TitleView作为中间部分,Collectionview作为下面部分,实现了滚动效果。同时还介绍了使用runtime拦截_notifyDidScroll方法来实现滚动代理的方法。具体实现代码可以在github地址中找到。 ... [详细]
  • iOS Swift中如何实现自动登录?
    本文介绍了在iOS Swift中如何实现自动登录的方法,包括使用故事板、SWRevealViewController等技术,以及解决用户注销后重新登录自动跳转到主页的问题。 ... [详细]
  • IOS开发之短信发送与拨打电话的方法详解
    本文详细介绍了在IOS开发中实现短信发送和拨打电话的两种方式,一种是使用系统底层发送,虽然无法自定义短信内容和返回原应用,但是简单方便;另一种是使用第三方框架发送,需要导入MessageUI头文件,并遵守MFMessageComposeViewControllerDelegate协议,可以实现自定义短信内容和返回原应用的功能。 ... [详细]
  • 如何在php文件中添加图片?
    本文详细解答了如何在php文件中添加图片的问题,包括插入图片的代码、使用PHPword在载入模板中插入图片的方法,以及使用gd库生成不同类型的图像文件的示例。同时还介绍了如何生成一个正方形文件的步骤。希望对大家有所帮助。 ... [详细]
  • 本文介绍了如何使用PHP代码将表格导出为UTF8格式的Excel文件。首先,需要连接到数据库并获取表格的列名。然后,设置文件名和文件指针,并将内容写入文件。最后,设置响应头部,将文件作为附件下载。 ... [详细]
  • 本文介绍了ASP.NET Core MVC的入门及基础使用教程,根据微软的文档学习,建议阅读英文文档以便更好理解,微软的工具化使用方便且开发速度快。通过vs2017新建项目,可以创建一个基础的ASP.NET网站,也可以实现动态网站开发。ASP.NET MVC框架及其工具简化了开发过程,包括建立业务的数据模型和控制器等步骤。 ... [详细]
  • 本文讨论了在ASP中创建RazorFunctions.cshtml文件时出现的问题,即ASP.global_asax不存在于命名空间ASP中。文章提供了解决该问题的代码示例,并详细解释了代码中涉及的关键概念,如HttpContext、Request和RouteData等。通过阅读本文,读者可以了解如何解决该问题并理解相关的ASP概念。 ... [详细]
author-avatar
杜伟丿2552
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有