• addSubView需要注意的几个点


    addSubview:

    Adds a view to the end of the receiver’s list of subviews.

    :增加一个视图到接收者的子视图列表中。


    - (void)addSubview:(UIView *)view

    Parameters

    view

    The view to be added. This view is retained by the receiver. After being added, this view appears on top of any other subviews.

    :view参数代表被增加的view,这个view会被它的接收者retain一次(即引用计数+1)。增加完成之后,这个view将出现在接收者的其他子视图的上面。

    ps:关于子视图的出现的层次的问题,可以从这些子视图被保存的数据结构来探寻答案 ,每个视图都有个数组的属性,subviews,这个就是保存的它的子视图的引用。而这个数组的顺序就是代表了各个子视图被加入时的顺序。index=0 的就是最先被加入进去的,以此类推。所以,索引值越高的视图越不容易被覆盖。


    Discussion

    This method retains view and sets its next responder to the receiver, which is its new superview.

    这个方法会retain一次view,并且设置它的下一个响应者是receiver,即它的新的父视图。

    ps:在removeFromSuperview里已经说过,其实视图直接的操作往往牵涉到两个方面的操作,一个是视图的数据结构,一个是响应者链。当然,addsubview也不例外。


    Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.

    :每一个视图只能有唯一的一个父视图。如果当前操作视图已经有另外的一个父视图,则addsubview的操作会把它先从上一个父视图中移除(包括响应者链),再加到新的父视图上面。


    Availability

    • Available in iOS 2.0 and later.

    See Also

      • – insertSubview:atIndex:
      • – insertSubview:aboveSubview:
      • – insertSubview:belowSubview:
      • – exchangeSubviewAtIndex:withSubviewAtIndex:

     

     

    addSubview和insertSubview的区别

    addSubview 是将view加到所有层的最顶层

    相当于将insertSubview的atIndex参数设置成view.subviews count

    [view addSubview:oneview] == [view insertSubview:oneview atIndex:view.subviews count]

     

    addSubview是加到最后
    insertSubview是加到指定的位置

     

    为什么要在addsubview:一个view对象后,release它?

    先看代码:

    1
    2
    3
    
    IMGView *imgView = [[IMGView alloc] initWithFrame:CGRectMake(10, 0, 300, 300)];
    [self.view addSubview:imgView];
    [imgView release];

    为什么imgView要release呢?可能很多人跟我一样,之前不是很清楚。 我们逐行分析一下

    第一行,alloc一次,imgView对象retainCount为1,
    第 二行,addSubview一次,此方法会把你传过去的对象retain一次,那么此时它的retainCount为2。self.view变为它的第二 个待有者。参考:The receiver retains view. If you use removeFromSuperview to remove view from the view hierarchy, view is released.
    第三行,调用release方法,此处释放对imgView的所有权,retainCount减1。

    到语言句尾imgView的所有者只剩下self.view,并且它的retainCount仅为1。内存管理第一铁则,谁retain(alloc,copy)谁release(autorelease)。上述的做法也是为了符合这一准则。

  • 相关阅读:
    前三次复利计算程序的总结
    Compound Interest Calculator3.0
    Compound Interest Calculator2.0
    Compound Interest Calculator1.0
    操作系统第一次作业
    学习进度条
    0302感想和问题回答
    1231递归下降语法分析程序设计
    1211有限自动机构造与识别
    5份Java面经
  • 原文地址:https://www.cnblogs.com/heyonggang/p/3470550.html
Copyright © 2020-2023  润新知