Iphone笔记(3)

简介: 1 关于属性的.和setXXX( ) 比如一个类在.h文件中有一个属性@property (nonatomic, retain) UIImage *photo; 在其.
1 关于属性的.和setXXX( )
比如一个类在.h文件中有一个属性@property (nonatomic, retain) UIImage *photo;
在其.m文件中可以写一个方法:
-(void)setPhoto:(UIImage *) nowPhoto{
    nowPhotoSize=nowPhoto.size;
    self.imageView.image=nowPhoto; 
    self.tempNowPhoto=nowPhoto;
    [self displayImage];
}
当在其他类中为该类对象的photo属性赋值的时候会调用setPhoto方法.
比如在写:innerScrollView.photo=[self.delegate galleryImage:self filenameAtIndex:index];
此时就会去调用setPhoto方法,所以在setPhoto方法里面可以写一些需要的逻辑.这点很重要!!!!!!
当然也可以不在.m文件中不写setPhoto方法.这样在对其属性赋值的时候就不会带来其他额外的操作.只是本本分分地赋值而已.

2 点击UIScrollView放大,效果:双击某点以该点进行放大和缩小
//双击时调用该方法
//在此方法中 利用 [self zoomToRect:zoomRect animated:YES]; 指定了此UIScrollView进行缩放的区域
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{   
    UITouch* touch = [touches anyObject];
    if ([touch tapCount] == 1) {
        [self.eventDelegate didTouched:self];
}
else if ([touch tapCount] == 2) {
[self.eventDelegate didDoubleTouched:self];
    if (self.zoomScale == self.maximumZoomScale) {
            //点击后缩小执行此方法
            [self setZoomScale:self.minimumZoomScale animated:YES];
            //最新添加的 否则在横屏幕双击后 再双击 就会不正常
            self.maximumZoomScale=2.0;
        } else {
           CGRect zoomRect;  
            zoomRect = [self zoomRectForScrollView:self
                             withScale:self.maximumZoomScale
                             withCenter:[touch locationInView:self]];
            
            [self zoomToRect:zoomRect animated:YES];       
        }  
}
}

//zoomRectForScrollView方法如下
//返回此ScrollView进行缩放的区域
//注意:
//1 center是点击处的坐标!!!!!!!!!借此来确定zoomRect.origin.x和y  
//  这样也就可以保证点击放大后被点处处于此zoomRect缩放区域内 这样就达到了一个放大的效果
//2 横竖屏幕转换的时候最大maximumZoomScale应该有一个转换.比如竖屏幕转到横屏幕的时候应该重新设置self.maximumZoomScale=2.0*320.0f/480.0f;
//  就是说在横屏下最大缩放因子不能再是竖屏的2.0,应该比2.0要小否则显示起来很唐突.因为横屏的时候屏幕本来就很宽再按照2.0放大就很不好看了
- (CGRect)zoomRectForScrollView:(UIScrollView *)scrollView withScale:(float)scale withCenter:(CGPoint)center {
    CGRect zoomRect;
    if (self.bounds.size.width<400) {
        self.maximumZoomScale=1.0;
        zoomRect.size.height = scrollView.frame.size.height / scale;
        zoomRect.size.width  = scrollView.frame.size.width  / scale;
        zoomRect.origin.x = (center.x-(zoomRect.size.height/4))*2;
        zoomRect.origin.y = (center.y-(zoomRect.size.width/4))*2;  
    }else{
        self.maximumZoomScale=2.0*320.0f/480.0f;
        zoomRect.size.height = scrollView.frame.size.width / scale;
        zoomRect.size.width  = scrollView.frame.size.height  / scale;
        zoomRect.origin.x = (center.x-(zoomRect.size.width/4))*2*320/480;
        zoomRect.origin.y = (center.y-(zoomRect.size.height/4))*2*320/480;
    }
    return zoomRect;
}

3 设置UIScrollView在横竖屏幕下不同的缩放因子
//注意:
//1 要先设置self.minimumZoomScale=minScale;和self.maximumZoomScale=2.0;
// 再设置self.zoomScale=minScale;否则self.zoomScale=minScale;不起作用
//2 至于maxScale取MAX还是MIN应该根据业务需求而定
//3 继承自UIScrollView应该实现其对应的协议  即: @interface XCGalleryInnerScrollView : UIScrollView <UIScrollViewDelegate>
//4 尤其要注意UIScrollViewDelegate的一个方法-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView
//5 该方法返回的是需要进行缩放的控件,若不实现此方法,则无法进行缩放
//6 self.scrollView.clipsToBounds = NO;就是当取值为YES时,剪裁超出父视图范围的子视图部分;当取值为NO时,不剪裁子视图。默认值为NO
//7 重点!!!!在设置完缩放因子以后应该[self setNeedsLayout];相对于刷新
- (void)displayImage{
    self.maximumZoomScale=1.0;
    self.minimumZoomScale=1.0;
    self.zoomScale=1.0;
    self.contentSize = CGSizeMake(0, 0);
    
    CGRect photoImageViewFrame;
    photoImageViewFrame.origin=CGPointZero;
    photoImageViewFrame.size=nowPhotoSize;
    //将imageView.frame设置为图片的大小
    self.imageView.frame=photoImageViewFrame;
    //将innerScrollView.contentSize设置为图片的大小
    self.contentSize=photoImageViewFrame.size;
    //将此ScrollerView设置为自动缩放即随着父类自动缩放
    self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    CGFloat xScale = self.bounds.size.width / self.imageView.frame.size.width;
    CGFloat yScale = self.bounds.size.height / self.imageView.frame.size.height; 
    CGFloat maxScale;
    if (self.bounds.size.width<400) {
         maxScale = MIN(xScale, yScale);
    }else{
         maxScale = MAX(xScale, yScale);
    }
    self.maximumZoomScale=2.0;
    self.minimumZoomScale=maxScale;
    self.zoomScale=maxScale;
    [self setNeedsLayout];
}

4 在某个时间后,让某些控件消失的时带有UIView动画,实现淡出的效果
//指定在三秒钟后调用hideBar实现控件隐藏
- (void)aMethod{
   self.slider_timer = [NSTimer
                         scheduledTimerWithTimeInterval:3.0f
                         target:self
                         selector:@selector(hideBar:)
                         userInfo:nil
                         repeats:NO
                         ];
}
//在该方法中让某些控件消失实际上是改变了它的frame,让其坐标在屏幕外.从而达到隐藏效果
- (void)hideBar:(NSTimer*)time{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
  
    self.back_tb.frame = CGRectMake(0, 480, 320, 40);
    self.tb.toolbar.frame = CGRectMake(0, 520, 320, 50);
        
    [UIView commitAnimations];
    [self.delegate hideADBanner];
    //注意在隐藏后应该让slider_timer设置为invalidate即不可用
    [self.slider_timer invalidate];
}

5 设置UINavigationController的toolbar中的内容
    //其实是可以设置UINavigationController的toolbar的frame和内容.当然通常是在屏幕下方
    //得到toolbar
    self.tb.toolbar.frame = CGRectMake(0, 435, 320, 50);
    //生成一个带有图片的UIBarButtonItem
    UIBarButtonItem *books = [[UIBarButtonItem alloc]
                              initWithImage:[UIImage imageNamed:@"books_icon_20x20.png"]
                              style:UIBarButtonItemStylePlain
                              target:self
                              action:@selector(booksButtonClicked)];
    //生成一个UILabel
    self.lbl = [[UILabel alloc] initWithFrame:CGRectMake(45,0,240,50)];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.textColor = [UIColor whiteColor];
    lbl.textAlignment = UITextAlignmentCenter;
    //利用UILabel生成的UIBarButtonItem!!!!!!!!!!!!!(这个很重要)
    UIBarButtonItem *lblbtn = [[[UIBarButtonItem alloc] initWithCustomView: lbl] autorelease];

    //生成一个空白的占位符
    UIBarButtonItem *fixspacer = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace
                                                                                target: nil
                                                                                action: nil] autorelease];
    //所以:UINavigationController的toolbar一共显示了三个小控件 1可以收缩的空白占位符 2一个显示页面的UILabel 3一个UIBarButtonItem显示书架按钮
        //设置toolbar的items
    self.tb.toolbar.items = [NSArray arrayWithObjects: fixspacer, lblbtn, books, nil];

小结:
(1)从这里可以看出来,toolbar里面放的全部是UIBarButtonItem!!!!!!!!!
(2)很重要的一个问题::当画面刚显示出来后三秒, Label会出现一个微小的位移(本质上是Label中的文字发生了微小的位移,位移后文字会在Label中居中显示).造成画面抖动的错觉.
     解决办法:应该让此Label的高度与UINavigationController的toolbar的高度保持一致!!!!!!!!!!!!!!!

6  设置状态栏为半透明
 self.wantsFullScreenLayout = YES; 
 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:YES];

7 按下home键程序进入后台,然后再次进入应用的操作
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIApplication *app=[UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                          selector:@selector(applicationDidBecomeActive:) 
                                          name:UIApplicationWillEnterForegroundNotification 
                                          object:app];   
}
//覆写UIApplicationDelegate中的方法
- (void)applicationDidBecomeActive:(UIApplication *)application{
    //业务逻辑的操作
}

8 横竖屏幕切换的问题小结
//1 必须要实现此方法,并且返回YES,表示支持屏幕的切换
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{   
    [super shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait||toInterfaceOrientation==UIDeviceOrientationPortraitUpsideDown){
       //竖屏的操作       
    }else
    {
       //横屏的操作 
    }

    return YES;
}
//2 在执行完shouldAutorotateToInterfaceOrientation方法后会调用此方法
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {  
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait||self.interfaceOrientation==UIDeviceOrientationPortraitUpsideDown){
        //竖屏的操作  
     }else
    {
      //横屏的操作
    }
}

//以为一种错误的方法:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration 
  { 调用viewWillLayoutSubviews }
- (void)viewWillLayoutSubviews
  { 屏幕切换的操作 }
//错误原因及其现象:在屏幕切换的后第一次单击屏幕居然会调用viewWillLayoutSubviews方法!!!!从而造成一下莫名其妙的错误.

9 CATransaction动画 页面跳转时候的动画---新页面从右至左出现
  [CATransaction begin];
  [CATransaction setValue: (id)kCFBooleanTrue forKey: kCATransactionDisableActions];
  [self.navigationController.view.layer removeAllAnimations];
  CATransition *transition = [CATransition animation];
  [transition setType: kCATransitionPush];
  [transition setSubtype: kCATransitionFromRight];
  [self.navigationController.view.layer addAnimation: transition forKey: @"popAnimation"];
  [self.navigationController popViewControllerAnimated: NO];
  [CATransaction commit];

10 依据tag找到控件
 UIView *adView = [self.view viewWithTag: 1985];

11 关于plist文件的读取和修改
(1) 将plist文件的Item的Type设置为Dictionary

(2) 利用此plist生成数组且保存到NSUserDefaults中
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *booksData = [[NSArray alloc] initWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"books" ofType: @"plist"]];
[defaults setObject: booksData forKey: @"BOOKS"];

(3) 数据的读取
 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 NSArray *tmp = [defaults arrayForKey:@"BOOKS"];
 //依据id找到数组中的字典保存到字典self.infoData
 self.infoData = [tmp objectAtIndex:self.content_id];
 //从字典中获取某个值 
 NSInteger *tempId= [infoData objectForKey:@"id"] intValue];

(4) 修改保存在NSUserDefaults中的数据
- (void)writeStatus: (int) statusNumber toIndex: (int)indexNumber
{
    //找到NSUserDefaults中保存的数组
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *booksData = [NSMutableArray arrayWithArray: [defaults arrayForKey: @"BOOKS"]];
    //按照indexNumber取得字典生成一个可变字典NSMutableDictionary
    NSMutableDictionary* rowDict = [[booksData objectAtIndex: indexNumber] mutableCopy];
    //改变可变字典NSMutableDictionary中的某个值
    [rowDict setValue: [NSString stringWithFormat: @"%d", statusNumber] forKey: @"status"];
    //利用变化后的可变字典NSMutableDictionary替换数组中原来的对象
    [booksData replaceObjectAtIndex: indexNumber withObject: rowDict];
    //重新将数据保存到NSUserDefaults中
    [defaults setValue: booksData forKey: @"BOOKS"];
    //NSUserDefaults的同步
    [defaults synchronize];
}

12 设置UIImageView的图片
 UIImageView* loadingView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"loading.png"]];


13 自定义UITableView的Cell
许多时候需要自定义UITableView的Cell来达到目的,也可以采用cell的contentView属性来实现
比如:[cell.contentView addSubview:xxx];
这里的xxx均为UIView的子类对象

14 页面跳转时携带数据
要从现则的页面跳转到下一个页面ContentViewController但是要携带一些数据过去,可以这么做:
在ContentViewController.h中设置一个属性,这样就可以携带过去.例子:
ContentViewController.h中设置
@property uint content_id;
当前页面操作:
ContentViewController *content = [[ContentViewController alloc] init];
content setContent_id: bookIndex];
[self.navigationController pushViewController: content animated: NO];

15 UIAlertView的操作小技巧
问题描述:在同一个页面点击多出可能会弹出来多个UIAlertView,在点击UIAlertView上的确定按钮又要触发不同的操作
解决办法:
(1)此Controller.h实现UIAlertViewDelegate
(3)在每次需要弹出UIAlertView修改全局变量alertMode的值,例如:
alertMode = 3;
[self showLoading];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: nil 
                                                message: @"解凍中です、少々お待ちください"//データの解凍を行います。少々お待ちください。
                                                delegate: self 
                                       cancelButtonTitle: nil
                                       otherButtonTitles: @"OK", nil];//点击OK 后开始解压 并且在解压完成后里面进入该漫画书
[alert show];
[alert release];
(3)在Controller.m覆写- (void)alertView: (UIAlertView *)alertView didDismissWithButtonIndex: (NSInteger)buttonIndex
{
    if(alertMode=xx){
          //根据alertMode值的不同进行不同的操作
       }
}

16 在Documents下创建目录以及保存文件
//在Documents下创建目录
+ (void)createDirector: (NSString*)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileExists = [fileManager fileExistsAtPath: path];
    
if (!fileExists) {
[fileManager createDirectoryAtPath: path withIntermediateDirectories: YES attributes: nil error: nil];
}
}

//在Documents下保存文件
//得到Documents的路径
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 //利用文件名组拼目的地路径
 NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myimage.png"];
 UIImage *myimage=[UIImage imagenamed:@"myimage.png"];
 NSData *imageData = UIImagePNGRepresentation(myimage);      
 [imageData  writeToFile:filePath atomically:NO];  




2012年10月26日09:30:36

相关文章
|
Web App开发 缓存 开发工具
|
iOS开发
Iphone笔记(4)
1 关于字典的常见操作     NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:@"小明",@"name",@"1392711589",@"tel",@"b...
794 0
|
iOS开发
Iphone笔记(2)
关于IB的连接 1 给xib设定类,即指定它是哪个类的视图 2 把控件和.h文件中的IBOutlet类型对应的控制相连 3 把控件的点击方法和.
761 0
|
XML 数据格式 iOS开发
Iphone笔记(1)
    1 自定义UITableViewCell 1.(1)要注意给此Cell设置大小.      [self setFrame:CGRectMake(0, 0, 320, 120)]; 1.
789 0
|
iOS开发
iphone开发笔记——Cocos2d CCLayer中的touch
废话不多说,cocos2d 自带有两套协议 分别是CCTargetedTouchDelegate 和 CCStandardTouchDelegate 这两个都是处理touch inside 但是针对点不同, CCTargeted...这个协议针对单点触控,用户直接操作UITouch 而Standard 传入的是一个NSSet  里面是 当前屏幕触摸的每个触摸点的UITouch ,恩
1282 0
|
编解码 iOS开发
iphone 开发的基本入门知识
iphone 开发的基本入门知识
156 0
「镁客早报」iPhone或将在今年采用三摄;传Facebook致力于开发语音助力服务与亚马逊、苹果竞争
亚马逊向美国Alexa设备推免费音乐服务;视频会议软件开发商Zoom纳斯达克上市。
229 0