文章目录
  1. 1. iPhone代码片段收集

iPhone代码片段收集

Iphone学习笔记

iPhone代码片段收集

http://yueding920.blog.163.com/blog/static/352508902011234836265/

1. stringWithFormat 用法:
     [NSString stringWithFormat:@”Hight: %d°%@   Low: %d°%@”, [Temp],@”C”,[lTemp],@”C”];
       NSString to NSData:

NSString* str= @”kilonet”;

NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];

     2. NSDate 用法:

         NSDate  *today;

    NSDate tomorrow;
    today = [NSDate date];
    tomorrow = [NSDate dateWithTimeInterval:(i
246060) sinceDate:today]; //可能有更好的
         Date format用法:

  -(NSString *) getDay:(NSDate *) d {

    NSString *s ;
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@”YYYY/MM/dd hh:mm:ss”];
    s = [format stringFromDate:d];
    [format release];
    return s;
}
    各地时区获取:

-22.gif

代码
    NSDate *nowDate = [NSDate new];
    NSDateFormatter formatter    =  [[NSDateFormatter alloc] init];
    [formatter    setDateFormat:@”yyyy/MM/dd HH:mm:ss”];
    //    根据时区名字获取当前时间,如果该时区不存在,默认获取系统当前时区的时间
    //    NSTimeZone
 timeZone = [NSTimeZone timeZoneWithName:@”Europe/Andorra”];
    //    [formatter setTimeZone:timeZone];
    //获取所有的时区名字
    NSArray array = [NSTimeZone knownTimeZoneNames];
    //    NSLog(@”array:%@”,array);
    //for循环
    //    for(int i=0;i<[array count];i++)
    //    {
    //        NSTimeZone
 timeZone = [NSTimeZone timeZoneWithName:[array objectAtIndex:i]];
    //        [formatter setTimeZone:timeZone];
    //        NSString *locationTime = [formatter stringFromDate:nowDate];
    //        NSLog(@”时区名字:%@   : 时区当前时间: %@”,[array objectAtIndex:i],locationTime);
    //        //NSLog(@”timezone name is:%@”,[array objectAtIndex:i]);
    //    }
    //快速枚举法
    for(NSString *timeZoneName in array){
        [formatter setTimeZone:[NSTimeZone timeZoneWithName:timeZoneName]];
        NSLog(@”%@,%@”,timeZoneName,[formatter stringFromDate:nowDate]);
    }
    [formatter release];
    [nowDate release];
     获取毫秒时间:

代码
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    //[dateFormatter setDateFormat:@”hh:mm:ss”]
    [dateFormatter setDateFormat:@”yyyy-MM-dd HH:mm:ss.SSS”];
    NSLog(@”Date%@”, [dateFormatter stringFromDate:[NSDate date]]);
    [dateFormatter release];
      3. NSCalendar用法:

 -(NSString *) getWeek:(NSDate *) d {

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSWeekdayCalendarUnit;
    NSDateComponents *components = [calendar components:units fromDate:d];
    [calendar release];
    switch ([components weekday]) {
        case 2:
            return @”Monday”;
            break;
        case 3:
            return @”Tuesday”;
            break;
        case 4:
            return @”Wednesday”;
            break;
        case 5:
           return @”Thursday”;
            break;
        case 6:
            return  @”Friday”;
            break;
        case 7:
            return  @”Saturday”;
            break;
        case 1:
            return @”Sunday”;
            break;
        default:
            return @”No Week”;
            break;
    }

    // 用components,我们可以读取其他更多的数据。
}
      4. 用Get方式读取网络数据:

// 将网络数读取为字符串
- (NSString *) getDataByURL:(NSString *) url {
    return [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding];
}

//读取网络图片
- (UIImage *) getImageByURL:(NSString *) url {
    return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
}

     5. 多线程NSThread用法 :

[NSThread detachNewThreadSelector:@selector(scheduleTask) toTarget:self withObject:nil];

-(void) scheduleTask {
    //create a pool
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //release the pool;
    [pool release];
}

//如果有参数,则这么使用:
[NSThread detachNewThreadSelector:@selector(scheduleTask:) toTarget:self withObject:[NSDate date]];

-(void) scheduleTask:(NSDate *) mdate {
    //create a pool
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //release the pool;
    [pool release];
}

//注意selector里有冒号。
    //在线程里运行主线程里的方法

    [self performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];
      6. 定时器NSTimer用法:

-23.gif

代码
  // 一个可以自动关闭的Alert窗口

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:[@”一个可以自动关闭的Alert窗口”
                                                   delegate:nil
                                          cancelButtonTitle:nil //NSLocalizedString(@”OK”, @”OK”)   //取消任何按钮
                                          otherButtonTitles:nil];
    //[alert setBounds:CGRectMake(alert.bounds.origin.x, alert.bounds.origin.y, alert.bounds.size.width, alert.bounds.size.height+30.0)];
    [alert show];
    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    // Adjust the indicator so it is up a few pixels from the bottom of the alert
    indicator.center = CGPointMake(alert.bounds.size.width/2,  alert.bounds.size.height-40.0);
    [indicator startAnimating];
    [alert insertSubview:indicator atIndex:0];
    [indicator release];
    [NSTimer scheduledTimerWithTimeInterval:3.0f
                                     target:self
                                   selector:@selector(dismissAlert:)
                                   userInfo:[NSDictionary dictionaryWithObjectsAndKeys:alert, @”alert”, @”testing “, @”key” ,nil]  //如果不用传递参数,那么可以将此项设置为nil.
                                    repeats:NO];

    NSLog(@”release alert”);
    [alert release];

-(void) dismissAlert:(NSTimer *)timer{
    NSLog(@”release timer”);
    NSLog([[timer userInfo]  objectForKey:@”key”]);
    UIAlertView *alert = [[timer userInfo]  objectForKey:@”alert”];
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}

       定时器停止使用:

        [timer invalidate];
        timer = nil;
     7. 用户缺省值NSUserDefaults读取:

    //得到用户缺省值
    NSUserDefaults defs = [NSUserDefaults standardUserDefaults];
    //在缺省值中找到AppleLanguages, 返回值是一个数组
    NSArray
 languages = [defs objectForKey:@”AppleLanguages”];
    NSLog(@”all language语言 is %@”, languages);
    //在得到的数组中的第一个项就是用户的首选语言了
    NSLog(@”首选语言 is %@”,[languages objectAtIndex:0]);

    //get the language & country code
    NSLocale *currentLocale = [NSLocale currentLocale];
    NSLog(@”Language Code is %@”, [currentLocale objectForKey:NSLocaleLanguageCode]);
    NSLog(@”Country Code is %@”, [currentLocale objectForKey:NSLocaleCountryCode]);
     8. View之间切换的动态效果设置:

    SettingsController *settings = [[SettingsController alloc]initWithNibName:@”SettingsView” bundle:nil];
    settings.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;  //水平翻转
    [self presentModalViewController:settings animated:YES];
    [settings release];
     9.NSScrollView 滑动用法:

-(void) scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@”正在滑动中…”);
}

//用户直接滑动NSScrollView,可以看到滑动条
-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

}

// 通过其他控件触发NSScrollView滑动,看不到滑动条
- (void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {

}
    10. 读取全局的Delegate:

KiloNetAppDelegate *appdelegate = (KiloNetAppDelegate *)[[UIApplication sharedApplication] delegate];

     11.键盘处理系列

 //set the UIKeyboard to switch to a different text field when you press return

//switch textField to the name of your textfield
[textField becomeFirstResponder];
     12. 半透明层的实现:

-24.gif

半透明层
+(void)showWaiting:(UIView )parent {
    int width = 32, height = 32;
    CGRect frame = [parent frame]; //[[UIScreen mainScreen] applicationFrame];
    int x = frame.size.width;
    int y = frame.size.height;
    frame = CGRectMake((x - width) / 2, (y - height) / 2, width, height);
    UIActivityIndicatorView
 progressInd = [[UIActivityIndicatorView alloc] initWithFrame:frame];
    [progressInd startAnimating];
    progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
//    frame = CGRectMake((x - 140)/2, (y - height) / 2 + height, 140, 30);
//    UILabel *waitingLable = [[UILabel alloc] initWithFrame:frame];
//    waitingLable.text = @”Proccesing…”;
//    waitingLable.textColor = [UIColor whiteColor];
//    waitingLable.font = [UIFont systemFontOfSize:15];
//    waitingLable.backgroundColor = [UIColor clearColor];
    frame = [parent frame];
    UIView *theView = [[UIView alloc] initWithFrame:frame];
    theView.backgroundColor = [UIColor blackColor];
    theView.alpha = 0.8;
    [theView addSubview:progressInd];
//  [theView addSubview:waitingLable];
    [progressInd release];
//    [waitingLable release];
    [theView setTag:9999];
    [parent addSubview:theView];
    [theView release];
}

+(void)hideWaiting:(UIView *)parent {
    [[parent viewWithTag:9999] removeFromSuperview];
}
      13. 设置View的圆角:

 // 首先应用  #import <QuartzCore/QuartzCore.h>

view.layer.cornerRadius = 10;
view.layer.masksToBounds = YES;
      14. UIWebView显示本地图片(目前有点问题,无法正确显示图片):

%!(EXTRA markdown.ResourceType=, string=, string=)

代码
    NSString *imagePath = [[NSBundle mainBundle] resourcePath];
    imagePath = [imagePath stringByReplacingOccurrencesOfString:@”/“ withString:@”//“];
    imagePath = [imagePath stringByReplacingOccurrencesOfString:@” “ withString:@”%20”];
    NSLog(@”fileurl=%@”,[NSString stringWithFormat:@”file:/%@//“,imagePath]);
    //[self loadData:[html dataUsingEncoding:NSUTF8StringEncoding] MIMEType:@”text/html” textEncodingName:@”UTF-8” baseURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@”file:/%@//“,imagePath]] ];
    [self loadHTMLString:html baseURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@”file:/%@//“,imagePath]   ]];
     NSString *path = [[NSBundle mainBundle] bundlePath];

    NSURL *baseURL = [NSURL fileURLWithPath:path];
    [UIWebView loadHTMLString:html baseURL:baseURL];
    //这段代码可以正确显示图片。

  1. 随机数:
    srandom(time(NULL)); //随机数种子

id d = random(); // 随机数
  2. 视频播放:

    MPMoviePlayerController *moviePlayer;
    moviePlayer = [[MPMoviePlayerController alloc]
                   initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@”Movie” ofType:@”m4v”]]];
    //初始化视频播放器对象,并传入被播放文件的地址
    moviePlayer.movieControlMode = MPMovieControlModeDefault;
    [moviePlayer play];
    //此处有内存溢出
   3.  启动界面显示:

iPhone软件启动后的第一屏图片是非常重要的往往就是loading载入中的意思。设置它说来也简单,但是却无比重要

只需要在resource里面将你希望设置的图片更名为Default.png,这个图片就可以成为iPhone载入的缺省图片

    4. iPhone的系统目录:

//得到Document目录:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//得到temp临时目录:
NSString *tempPath = NSTemporaryDirectory();

//得到目录上的文件地址:
NSString *文件地址 = [目录地址 stringByAppendingPathComponent:@”文件名.扩展名”];
    5. 状态栏显示Indicator:

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

  6.app Icon显示数字:

- (void)applicationDidEnterBackground:(UIApplication *)application{

    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:5];

}

   7.sqlite保存地址:

%!(EXTRA markdown.ResourceType=, string=, string=)

代码
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *thePath = [paths objectAtIndex:0];
    NSString *filePath = [thePath stringByAppendingPathComponent:@”kilonet1.sqlite”];
    NSString *dbPath = [[[NSBundle mainBundle] resourcePath]
                        stringByAppendingPathComponent:@”kilonet2.sqlite”];
   8.Application退出:exit(0);

      9. AlertView,ActionSheet的cancelButton点击事件:

%!(EXTRA markdown.ResourceType=, string=, string=)

代码
-(void) actionSheet :(UIActionSheet *) actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex {
    NSLog(@”cancel actionSheet……..”);
    //当用户按下cancel按钮
    if( buttonIndex == [actionSheet cancelButtonIndex]) {
        exit(0);
    }
//    //当用户按下destructive按钮
//    if( buttonIndex == [actionSheet destructiveButtonIndex]) {
//        // DoSomething here.
//    }
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
     NSLog(@”cancel alertView……..”);
    if (buttonIndex == [alertView cancelButtonIndex]) {
        exit(0);
    }
}
    10.给Window设置全局的背景图片:

window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@”coolblack.png”]];
    11. UITextField文本框显示及对键盘的控制:

%!(EXTRA markdown.ResourceType=, string=, string=)

代码
#pragma mark -
#pragma mark UITextFieldDelegate
//控制键盘跳转
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _txtAccount) {
        if ([_txtAccount.text length]==0) {
            return NO;
        }
        [_txtPassword becomeFirstResponder];
    } else if (textField == _txtPassword) {
        [_txtPassword resignFirstResponder];
    }
    return YES;
}

//输入框背景更换
-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField{
    [textField setBackground:[UIImage imageNamed:@”ctext_field_02.png”]];
    return YES;
}

-(void) textFieldDidEndEditing:(UITextField *)textField{
    [textField setBackground:[UIImage imageNamed:@”ctext_field_01.png”]];
}
    12.UITextField文本框前面空白宽度设置以及后面组合按钮设置:

%!(EXTRA markdown.ResourceType=, string=, string=)

代码
    //给文本输入框后面加入空白
    _txtAccount.rightView = _btnDropDown;
    _txtAccount.rightViewMode =  UITextFieldViewModeAlways;
    //给文本输入框前面加入空白
    CGRect frame = [_txtAccount frame];
    frame.size.width = 5;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    _txtAccount.leftViewMode = UITextFieldViewModeAlways;
    _txtAccount.leftView = leftview;
    13. UIScrollView 设置滑动不超出本身范围:

 [fcScrollView setBounces:NO];

     14. 遍历View里面所有的Subview:

%!(EXTRA markdown.ResourceType=, string=, string=)

代码
    NSLog(@”subviews count=%d”,[self.view.subviews count]);
    if ([self.view.subviews count] ]] >  0) {
        for (UIView *curView in self.view.subviews) {
                       NSLog(@”view.subviews=%@”, [NSString stringWithUTF8String:object_getClassName(curView)]);
        }
    }
    14. 在drawRect里画文字:

     UIFont * f = [UIFont systemFontOfSize:20];

    [[UIColor darkGrayColor] set];
    NSString * text = @”hi \nKiloNet”;
    [text drawAtPoint:CGPointMake(center.x,center.y) withFont:f];
    15. NSArray查找是否存在对象时用indexOfObject,如果不存在则返回为NSNotFound.

     16. NString与NSArray之间相互转换:

array = [string componentsSeparatedByString:@”,”];
string = [[array valueForKey:@”description”] componentsJoinedByString:@”,”];
     17. TabController随意切换tab bar:

[self.tabBarController setSelectedIndex:tabIndex];

或者 self.tabBarController.selectedIndex = tabIndex;

或者实现下面的delegate来扑捉tab bar的事件:

%!(EXTRA markdown.ResourceType=, string=, string=)

代码
-(BOOL) tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    if ([viewController.tabBarItem.title isEqualToString: NSLocalizedString(@”Logout”,nil)]) {
        [self showLogout];
        return NO;
    }
    return YES;
}

    18. 自定义View之间切换动画:

%!(EXTRA markdown.ResourceType=, string=, string=)

代码
- (void) pushController: (UIViewController*) controller
         withTransition: (UIViewAnimationTransition) transition
{
    [UIView beginAnimations:nil context:NULL];
    [self pushViewController:controller animated:NO];
    [UIView setAnimationDuration:.5];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationTransition:transition forView:self.view cache:YES];
    [UIView commitAnimations];
}
    或者:

%!(EXTRA markdown.ResourceType=, string=, string=)

代码
CATransition *transition = [CATransition animation];
transition.duration = kAnimationDuration;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromTop;
transitioning = YES;
transition.delegate = self;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
self.navigationController.navigationBarHidden = NO;
[self.navigationController pushViewController:tableViewController animated:YES];

      19. UIWebView加载时白色显示问题解决以及字体统一设置:

    uiWebView.opaque = NO;

%!(EXTRA markdown.ResourceType=, string=, string=)

代码

     20.计算字符串长度:

CGFloat w = [title sizeWithFont:[UIFont fontWithName:@”Arial” size:18]].width;

    21. iTunesLink should be your applications link

NSString *iTunesLink = @”http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=xxxxxx&mt=8“;

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];

    22.时间转换NSString & NSDate:

 -(NSDate *)NSStringDateToNSDate:(NSString *)string {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@”UTC”]];
    [formatter setDateFormat:@”yyyy-MM-dd”];
    NSDate *date = [formatter dateFromString:string];
    [formatter release];
    return date;
}
 NSString *year = [myDate descriptionWithCalendarFormat:@”%Y” timeZone:nil locale:nil];

or

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

[formatter setDateFormat:@”yyyy”];

//Optionally for time zone converstions

[formatter setTimeZone:[NSTimeZone timeZoneWithName:@”…”]];

NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];

22。 模拟器的文件位置

其中#username#表示当前用户名:
/Users/#username#/Library/Application Support/iPhone Simulator/User/Applications/

  23.在使用UISearchBar时,将背景色设定为clearColor,或者将translucent设为YES,都不能使背景透明,经过一番研究,发现了一种超级简单和实用的方法:

1

[[searchbar.subviews objectAtIndex:0]removeFromSuperview];

背景完全消除了,只剩下搜索框本身了。

  24.  图像与缓存 :

UIImageView *wallpaper = [[UIImageView alloc] initWithImage:
        [UIImage imageNamed:@“icon.png”]]; // 会缓存图片

UIImageView *wallpaper = [[UIImageView alloc] initWithImage:
        [UIImage imageWithContentsOfFile:@“icon.png”]]; // 不会缓存图片

  25. 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];

  1. UIPopoverController 使用

-(void) onSetting:(id) sender {

    SplitBaseController *detail = [[SettingServerController alloc] init];

    CGRect frame = [(UIView *)sender frame];

    frame.origin.y = 0;

    UIPopoverController *popwin = [[UIPopoverController alloc] initWithContentViewController:detail];

    [popwin setPopoverContentSize:CGSizeMake(400, 300) animated:YES];

    popwin.delegate = self;

    [popwin presentPopoverFromRect: frame inView:self.viewpermittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

    [detail release];

}

27.在UINavigationBar中添加左箭头返回按钮

在iPhone里面最讨厌的控件之一就是 UINavigationBar了。这个控件样式修改不方便,连添加按钮也特别麻烦。下面的例子是如何手动添加带箭头的按钮:

UINavigationItem *item = [navBar.items objectAtIndex:0];

UINavigationItem *back = [[UINavigationItem alloc] initWithTitle:@”Back”];

NSArray *items = [[NSArray alloc] initWithObjects:back,item,nil];

[navBar setItems:items];

  • (BOOL)navigationBar:(UINavigationBar *)navigationBar

shouldPopItem:(UINavigationItem *)item{

//在此处添加点击back按钮之后的操作代码

return NO;

}

iOS开发之按钮或图片框圆角处理

http://www.istar.name/blog/ios-radius

图片框圆角处理(UIImageView):
添加QuartzCore.framework
导入库头文件
#import “QuartzCore/QuartzCore.h”

//圆角设置
imageView.layer.cornerRadius = 8;(值越大,角就越圆)
imageView.layer.masksToBounds = YES;
//边框宽度及颜色设置
[imageView.layer setBorderWidth:2];
[imageView.layer setBorderColor:[UIColor blueColor]]; //设置边框为蓝色

//自动适应,保持图片宽高比
imageView.contentMode = UIViewContentModeScaleAspectFit;

http://www.oschina.net/p/uiglossybutton

 ### 自定义UITableViewCell的accessoryView 判断哪个Button按下

UITableview的开发中经常要自定义Cell右侧的AccessoryView,把他换成带图片的按钮,并在用户Tap时判断出是哪个自定义按钮被按下了。

创建自定义按钮,并设为AccessoryView

if (cell == nil) { 
    cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault                                  reuseIdentifier:identifier]; 
   
    UIImage *image= [ UIImage imageNamed:@"delete.png" ];
    UIButton *button = [ UIButton buttonWithType:UIButtonTypeCustom ];
    CGRect frame = CGRectMake( 0.0 , 0.0 , image.size.width , image.size.height );
    button. frame = frame;
    [button setBackgroundImage:image forState:UIControlStateNormal ];
    button. backgroundColor = [UIColor clearColor ];
    [button addTarget:self action:@selector(buttonPressedAction  forControlEvents:UIControlEventTouchUpInside]; 
    cell. accessoryView = button;
 } 

如果将Button加入到cell.contentView中,也是可以的。

cell.contentView addSubview:button];

在Tap时进行判断,得到用户Tap的Cell的IndexPath

- (void)buttonPressedAction  id)sender 
{ 
   UIButton *button = (UIButton *)sender; 
   (UITableViewCell*)cell = [button superview]; 
   int row = [myTable indexPathForCell:cell].row; 
} 

对于加到contentview里的Button, ```
(UITableViewCell*)cell = [[button superview] superview];


按扭样式

//加载前的方法。

-(void)viewDidLoad

{

    //加载a.png图片,a图片已加载到资源库。

    //用做平常状态的按钮样式。

    UIImage *buttonNormal =[UIImage imageNamed:@"a.png"];

    //保留12像素的边框,中间拉伸。

    UIImage *stretchableButtonImageNormal = [buttonNormal stretchableImageWithLeftCapWidth:12 topCapeight:0];

    //btn:按钮名

    //背景设置为已经配置好的图片(stretchableButtonImageNormal),并指示为正常状态。

    [btn setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];

    //点击后的按钮样式为b.png图片。

    UIImage *buttonPressed =[UIImage imageNamed:@"b.png"];

    //同上。

    UIImage *stretchableButtonImagePressed = [buttonPressed stretchableImageWithLeftCapWidth:12 topCapeight:0];

    //设置点击后的状态样式。

    [btn setBackgroundImage:stretchableButtonImagePressed forState:UIControlStateHighlighted];

}

如何添加页面的navigation Bar
# iOS如何让主界面不显示NavigationBar 

我看到好多应用都是主界面用类似九宫格显示。上面没有NavigationBar。而点击某个按钮后,跳转到下一个view,就显示了NavigationBar,还有返回按钮。很明显是NavigationController,可是我在iOS5的storyboard中无法让主界面不显示NavigationBar,只要加上NavigationController,在链中所有view都自动加上了NavigationBar。

//显示Navigation Bar
self.navigationController.navigationBarHidden = NO;

## IPhone之navigationItem

 (2010-12-09 21:35:34)[%!(EXTRA markdown.ResourceType=, string=, string=)

转载_▼_]()

|标签: ### [navigationitem](http://search.sina.com.cn/?c=blog&q=navigationitem&by=tag)

|分类: [IPhone](http://blog.sina.com.cn/s/articlelist_1256141290_14_1.html)|
|--------------------------------------------------------------------------------------|---------------------------------------------------------------------------|

**注:**

使用其navigationItem时,首先要确保UINavigationController 视图已经加载到ViewController中。

其代码为:

 

|[[UINavigationController alloc] initWithRootViewController:viewController];||
|---------------------------------------------------------------------------||

 

 

**1、添加按钮**

 

|UIBarButtonItem *loginBut =[[UIBarButtonItem alloc] initWithTitle:@"Login" style:UIBarButtonItemStylePlain target:self action:@selector(login)];   

    self.navigationItem.rightBarButtonItem = loginBut;   

    [loginBut release];

   

    UIBarButtonItem *createBut =[[UIBarButtonItem alloc] initWithTitle:@"NEW" style:UIBarButtonItemStylePlain target:self action:@selector(creatUser)];   

    self.navigationItem.leftBarButtonItem = createBut;   

    [createBut release];||
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------||

 

 

**2、添加segmentedControl**

 

|UISegmentedControl *m_segmentedControl = [[UISegmentedControl alloc] initWithItems:

                                            [NSArray arrayWithObjects:

                                            [UIImage imageNamed:@"up.png"],

                                            [UIImage imageNamed:@"down.png"],

                                            nil]];

    [m_segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];

    m_segmentedControl.frame = CGRectMake(0, 0, 90, 30);

    m_segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;

    m_segmentedControl.momentary = YES;

   

    UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:m_segmentedControl];

    [m_segmentedControl release];

   

    self.navigationItem.rightBarButtonItem = segmentBarItem;

    [segmentBarItem release];||
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------||

 

 

**3、设置标题**

 

| self.navigationItem.title = @"详细内容";||
|-----------------------------------------||

 

 

**4、设置返回按钮**

 

|self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"主菜单" style:UIBarButtonItemStylePlain target:nil action:nil] autorelease];

|
|--------------------------------------------------------------------------------------------------------------------------------------------------------------|

//对数组元素进行处理,不需要for循环出来处理
NSArray enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
文章目录
  1. 1. iPhone代码片段收集