iOS开发的技巧

iOS开发中的一些tips.

1.UITableView相关

当tableview数据源为空的时候,tableview会有多条分割线。如何消除分割线有两种

  • a.在tablview把separatorStyle 设置为 UITableViewCellSeparatorStyleNone,需要分割线的时候在自定义的cell view 底部手动加一个1像素高label
  • b.在初始化tableview后,设置tableview.tableFooterView = [[UIView alloc] init];
  • a.采用上面第一种方法,要注意2倍,3倍分辨率的屏幕上1像素线的画法

    #define SINGLE_LINE_WIDTH (1 / [UIScreen mainScreen].scale)
    #define SINGLE_LINE_ADJUST_OFFSET ((1 / [UIScreen mainScreen].scale) / 2)
    UIView *view = [[UIView alloc] initWithFrame:CGrect(x - SINGLE_LINE_ADJUST_OFFSET, 0, 320, SINGLE_LINE_WIDTH)];

    b.采用上面第二种方法后,需要自己维护tableview分割线的左间距,参考以下方法

    -(void)dealLineWithLeftInsert:(CGFloat)insert ///insert代表左间距是多少
    {
    #ifdef __IPHONE_7_0
    if ([self respondsToSelector:@selector(setSeparatorInset:)])[self setSeparatorInset:UIEdgeInsetsMake(0, insert, 0, 0)];
    #endif
    #ifdef __IPHONE_8_0
    if ([self respondsToSelector:@selector(setLayoutMargins:)])[self setLayoutMargins:UIEdgeInsetsMake(0, insert, 0, 0)];
    if ([self respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])[self setPreservesSuperviewLayoutMargins:NO];
    #endif
    }

    列表上的广告条,在一个列表展示数据的产品中,经常会在tableviewHeader有一个定时轮播的广告位(UIScrollView+NSTimer)。但是在滑动列表的时候,广告就会停止播放。

    只要把timer加在当前的runlooph 可以确保定时器正常执行

    [[NSRunLoop currentRunLoop] addTimer:《#(NSTimer *yourTimer)#》 forMode:NSRunLoopCommonModes>]

    2.UIView相关

    a.从view上把子视图移除

    [[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperview) withObject:nil];

    b.通过设置view的背影颜色透明,不影响子视频的透明度(如果设置父view的alpha值,子view也会继承父view的alpha)

     view.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.5]; //只是颜色带alpha,但是view自己的alpha不变

    c.view上的事件响应链

    响应链 (view) A[B, C [D,E] ]---这是一个视图的嵌套关关系ABCDE代表一个view,其中D,E的父view是C;B,C的父view是A,A是controller view
    当一个touch事件发生后,hit-testing是如果检测到哪个视图响应的
    如果touch点击的时候,是点击在view E里面。则检测过程是
    1.首先是touch点在view A的bounds中,接下来检测view B和view C.
    2.检测到touch点不在view B,在view C中,接下来检测view D和view E.
    3.检测到touch点不在view D中,在view E中。
    此时hit-testing过程已经完成,view E就是hit-test View.
    响应链的起始点是,hit-test view(起点)和UIApplication对象(终点)。传递的方向就是从最上面的view向下传递,如果view是view controller的view,还会经过view controller之后在向下传递,最终到达app对象. 响应链:E->C->A(A是viewcontroler's View)->Window->Application

    3.UITextField placeholder的颜色和位置

    继承uitextfield,重写这个方法
    - (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
    }

    3.UINavigationBar改变为透明

    [self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationBar.shadowImage = [UIImage new];
    self.navigationBar.translucent = YES;