ios 一个月以来的总结。。。

方法常用:

1,- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

2,- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

3,- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

4,- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

tableview 常用代理方法


staticNSString* courseIdentifier = @"CourseCell";

        CourseCell* cell = [tableView dequeueReusableCellWithIdentifier:courseIdentifier];

        if (!cell)

        {

            NSArray* array = [[UINibnibWithNibName:courseIdentifier bundle:nil] instantiateWithOwner:selfoptions:nil];

            cell = [array lastObject];

        }

 [self.mTableViewreloadData];

tableviewcell  重用,注意identifier,注意reloadData的含义,就是告诉tableview俺有数据需要加载了,有新的数据了。


-(IBAction)changeState:(id)sender

{

    

    UIButton *button = (UIButton *)sender;

    if (button.tag == 0) {

        [selfloadData_category:XIN_NEI_LAO_NIAN_KElastId:@""];

        buttonState = 0;

        [self.xinnei_buttonsetEnabled:NO];

        [self.shennei_buttonsetEnabled:YES];

        [self.daiding_buttonsetEnabled:YES];

        self.tempArray = self.xinnei_laonian_array;

        [self.mTableViewreloadData];

    }elseif (button.tag == 1) {

        [selfloadData_category:SHEN_NEI_KElastId:@""];

        buttonState = 1;

        [self.xinnei_buttonsetEnabled:YES];

        [self.shennei_buttonsetEnabled:NO];

        [self.daiding_buttonsetEnabled:YES];

        self.tempArray = self.shennei_array;

        [self.mTableViewreloadData];

    }elseif (button.tag == 2) {

        buttonState = 2;

        [self.xinnei_buttonsetEnabled:YES];

        [self.shennei_buttonsetEnabled:YES];

        [self.daiding_buttonsetEnabled:NO];

         self.tempArray = self.daiding_array;

        [self.mTableViewreloadData];

    }

}

状体改变,button 设置不同的状体,加载不同的数据


cell.contentView.backgroundColor = [[UIColoralloc] initWithRed:255/255.0

                                                                      green:248/255.0

                                                                       blue:240/255.0

                                                                      alpha:1];

设置cell背景颜色


[cell.lecturer1ButtonaddTarget:selfaction:@selector(turnToLectureIntroduce:) forControlEvents:UIControlEventTouchUpInside];

[cell.lecturer2ButtonaddTarget:selfaction:@selector(turnToLectureIntroduce:) forControlEvents:UIControlEventTouchUpInside];

手动给button连接对应事件,方法


 cell.lecturer1Button.tag = [indexPath row]*2;

 cell.lecturer2Button.tag = [indexPath row]*2+1;

 UIButton* button = (UIButton*)sender;

     Course *course = [self.tempArrayobjectAtIndex:button.tag/2];

    Teacher *teacher =nil;

    if (button.tag%2== 0) {

        teacher = [course.teachersobjectAtIndex:0];

    }else{

        teacher = [course.teachersobjectAtIndex:1];

    }

一个设置的小技巧,关于tag


 UIAlertView *alert = [[[UIAlertViewalloc] initWithTitle:@"只有登录后才能预约,是否进行登录?" message:nil delegate:selfcancelButtonTitle:nilotherButtonTitles:@"登录",@"取消", nil] autorelease];

        [alert show];


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 0){

        LoginViewController* controller = [[[LoginViewControlleralloc] init] autorelease];

        controller.isFromCourse = YES;

        controller.reservationButton = reservationButton;

        controller.executeReservationRquestDelegate = self;

        [SharedAppDelegate.window.rootViewControllerpresentModalViewController:controller animated:YES];

    }


alertview 外加一个代理使用


- (void)loadData_category:(NSString *)category lastId :(NSString *)lastId{

    NSString *deviceId = [[UIDevicecurrentDevice] uniqueGlobalDeviceIdentifier];

    NSString *userIdString = SharedAppDelegate.accountInfo.accountId;

    NSURL* url = [NSURLURLWithString:COURSEURL];

    AFHTTPClient* httpClient = [[AFHTTPClientalloc] initWithBaseURL:url];

    NSDictionary *param = [NSDictionarydictionaryWithObjectsAndKeys:

                           lastId,     @"last_id",

                           [NSStringstringWithFormat:@"%d", PAGESIZE],   @"page_size",

                           category,   @"class_name",

                           userIdString,@"userid",

                           deviceId,@"device_id",

                           nil];

    TTLog(@"params:%@", param);

    NSURLRequest* request = [httpClient requestWithMethod:@"POST"path:@""parameters:param];

    AFJSONRequestOperation *operation = [AFJSONRequestOperationJSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        [selfhiddenHUD];

        TTLog(@"response:%@", JSON);

        

        ResponseState *state = [ResponseStateresponseStateWithDic:JSON];

        courseHasMore = state.hasMore

                                            

   }failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

        TTLog(@"failed:%@", error);

        [selfhiddenHUD];

    }];

    [operation start];

    [selfshowHUD];

}


初始化一个dictionary,进行一次网络请求,注意这个过程是异步的,有时候可能出现数据不同步的现象。


a.h

@protocol ExecuteReservationRquestDelegate <NSObject>

-(void)reservation:(id)sender flag:(int)flag;


@end

@interface LoginViewController : BaseViewController <TencentSessionDelegate>

{

    NSString *openId;

}

a.m

  [self.executeReservationRquestDelegatereservation:self.reservationButtonflag:1];

@property (nonatomic,assign )id <ExecuteReservationRquestDelegate>executeReservationRquestDelegate;


@end

b.h

@interface CourseViewController : BaseViewController <UITableViewDataSource, UITableViewDelegate,UIAlertViewDelegate,ExecuteReservationRquestDelegate>

b.m

 controller.executeReservationRquestDelegate = self;


一个代理的使用


@interface NSDictionary(NullReplace)


- (id)valueForKeyNotNull:(NSString *)key;


@end


@interface ResponseState : NSObject


@property (retain, nonatomic) NSString *responseMessage;

@property (nonatomic) int responseCode;

@property (nonatomic) int hasMore;


@implementation NSDictionary(NullReplace)


- (id)valueForKeyNotNull:(NSString *)key{

    id object = [selfvalueForKey:key];

    if ([object isKindOfClass:[NSNumberclass]]

        || [object isKindOfClass:[NSStringclass]]

        || [object isKindOfClass:[NSArrayclass]]

        || [object isKindOfClass:[NSDictionaryclass]]) {

        return object;

    }

    returnnil;

}


@end


@implementation NSArray(NullReplace)


- (id)valueForKeyNotNull:(NSString *)key{

    returnnil;

}


@end


@implementation ResponseState

@synthesize responseCode;

@synthesize responseMessage;


+ (ResponseState *)responseStateWithDic:(NSDictionary *)dic{

    ResponseState *state = [[[ResponseStatealloc] init] autorelease];

    state.responseCode = [[dic valueForKeyNotNull:@"code"] intValue];

    state.responseMessage  = [dic valueForKeyNotNull:@"message"];

    state.hasMore = [[dic valueForKeyNotNull:@"has_more"] intValue];

   // state.newsId = [[dic valueForKeyNotNull:@"news_id"]];

    return state;

}


@end


一个model 以及对json的解析过程


+(NSString *)getFilePath

{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString* filePath = [documentsDirectory stringByAppendingPathComponent:FILENAME];

    return filePath;

}


//读取文件数据

+(NSString *)readFromFile

{

    NSError *error;

    NSString *filePath = [selfgetFilePath];

    NSString *stringData =  [NSStringstringWithContentsOfFile:filePath encoding:NSUTF8StringEncodingerror:&error];

    if (stringData == nil) {

        TTLog(@"read error %@",[error localizedFailureReason]);

        returnnil;

    }

    else{

        return stringData;

    }

}

+(BOOL)writeToFile_DataString:(NSString *)dataString

{

    

    NSError *error;

    NSString *filePath = [selfgetFilePath];

    return [dataString writeToFile:filePath atomically:YESencoding:NSUTF8StringEncodingerror:&error];

   

}


一个传说中的缓存,注意获取的是iphone手机上的doucument目录,可读可写


NSString *jsonString = [ReadWriteDataToFilereadFromFile];

    id JsonFromCache = [jsonString JSONValue];


 [ReadWriteDataToFilewriteToFile_DataString:[JSON JSONRepresentation]];

                self.xinnei_laonian_array = [CoursecourseListWithDic:JSON];

                self.tempArray = [CoursecourseListWithDic:JSON];

一个是将string 转为json,一个是将json转换为string,注意需要两个文件,#import "NSObject+SBJSON.h"#import "NSString+SBJSON.h",根据类名字可以判断是通过类别给它们类扩展的方法。


 NSString *deviceId = [[UIDevicecurrentDevice] uniqueGlobalDeviceIdentifier];#import "UIDevice+ID.h"

一获得deviceid 的方法


- (void)viewDidLoad

{

     [superviewDidLoad];

     [self.xinnei_buttonsetEnabled:NO];

     buttonState = 0;

     [selfloadDataFromCashe_JSON];

     [selfloadData_category:XIN_NEI_LAO_NIAN_KElastId:@""];

     [selfloadData_category:SHEN_NEI_KElastId:@""];

     [selfloadData_category:@""lastId:@""];

 }

注意viewdidload的加载顺序,viewdidload 应该写在前面。boss说的

self.navigationController popViewControllerAnimated:<#(BOOL)#>

self.navigationController pushViewController:<#(UIViewController *)#> animated:<#(BOOL)#>

viewcontroller presentModalViewController:<#(UIViewController *)#> animated:<#(BOOL)#>

viewcontroller dismissModalViewControllerAnimated:<#(BOOL)#>


关于controller的显示和隐藏,一个是在navigationcontroller 中的使用,一个是普通controller的使用


self.window = [[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]];

self.navigationController = [[[UINavigationControlleralloc] initWithRootViewController:self.tabBarController] autorelease];

self.window.rootViewController = self.navigationController; 

[self.windowmakeKeyAndVisible];

项目开始时候的加载,app delegate 有个win do w ,而window 有个rootviewcontroller 最初的梦想


  NSURL *url = [NSURLURLWithString:CONTENTINTRODUCE];

    NSURLRequest * request = [NSURLRequestrequestWithURL:url];

    [self.contentWebViewloadRequest:request];

    [superviewDidLoad];


webview 的加载


#pragma mark Setters


- (void)doneLoadingTableViewData{

    [moreButtonhideIndicator];

    reloading = NO;

    [self.tableViewreloadData];

[refreshHeaderViewegoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];

}


#pragma mark UIScrollViewDelegate Methods


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    [refreshHeaderViewegoRefreshScrollViewDidScroll:scrollView];

}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{

    [refreshHeaderViewegoRefreshScrollViewDidEndDragging:scrollView];

}


#pragma mark - EGERefreshTableHeaderViewDelegate Methods


- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{

    reloading = YES;

    [selfreloadTableViewDataSource];

}


- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{

returnreloading; // should return if data source model is reloading

}


- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{

return [NSDatedate]; // should return date data source was last changed

}


- (void)loadSubView{

    if (refreshHeaderView == nil) {

        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderViewalloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)] ;

        view.delegate = self;

        [self.tableViewaddSubview:view];

        refreshHeaderView = view;

        [view release];

    }

}

@end

EGORefreshTableHeaderDelegate

#import "EGORefreshTableHeaderView.h"

关于那个下拉刷新的效果对应的部分代码


@property (strong,nonatomic)IBOutletUIButton *hotSpotButton;

其中有些需要注意的就是,选择 strong= retain还是weak = assign,non atomic 是原子相关的。在需要的时候就用iboutlet插座变量,以便外面的变量来访问。据说版本不同,有的自动@synthesize

 initWithFrame:CGRectMake,cgsize里面有宽度有个高度 ,这个是调整大小的,以及相对位置, content isEqualToString:CGSize sizeOne = [teacher1.namesizeWithFont:cell.lecturer1Button.titleLabel.font];,计算字体的面积


关于控件大小的一些设置


 NSArray* array = [[UINibnibWithNibName:courseIdentifier bundle:nil] instantiateWithOwner:selfoptions:nil];

            cell = [array lastObject];

[UIViewController alloc]initWithNibName:<#(NSString *)#> bundle:<#(NSBundle *)#>;


策略:声明个变量记住一下自己想记住的信息。


原文地址:https://www.cnblogs.com/guligei/p/9029247.html