【问题标题】:iOS Programming Center Group of UIViewsiOS 编程中心组的 UIViews
【发布时间】:2013-02-16 15:12:32
【问题描述】:

我想知道如何/是否可以这样做:将一组 UIView 居中在一个超级视图中。最终结果将是一组明显居中在其超级视图中的视图。

【问题讨论】:

    标签: ios view uiview geometry centering


    【解决方案1】:

    嗯,这是一个两步的过程;首先将 UIViews 添加到数组中,然后快速枚举以将它们作为“组”居中

    //step 1: create the objects
    self.label1= [[UILabel alloc]init];
    self.label1.font=[UIFont systemFontOfSize:30.0];
    self.label1.text=@"1";
    
    self.label2= [[UILabel alloc]init];
    self.label2.font=[UIFont systemFontOfSize:30.0];
    self.label2.text=@"2";
    
    self.label3= [[UILabel alloc]init];
    self.label3.font=[UIFont systemFontOfSize:30.0];
    self.label3.text=@"3";
    
    
    //step2: create the array and add the objects to the array
    self.arrayOfViews=[[NSMutableArray alloc]initWithCapacity:4];
    [self.arrayOfViews addObject:self.label1];
    [self.arrayOfViews addObject:self.label2];
    [self.arrayOfViews addObject:self.label3];
    
    
    
    //step3: use fast enumeration to be able to control them as "group"
    for(UIView* currentViewObject in self.arrayOfViews)
    {
        currentViewObject.alpha=0.3;
        currentViewObject.frame=CGRectMake(self.view.bounds.size.width/2-sizeOfObject/2,self.view.bounds.size.height/2-sizeOfObject/2,sizeOfObject,sizeOfObject);
        [self.view addSubview:currentViewObject];
    }
    

    第 1 步和 alpha 设置仅用于测试目的。

    希望这会有所帮助。

    【讨论】:

    • initWithCapacity:4的目的是什么?
    • 使用前需要先分配初始化 NSMutableArray。可变数组根据需要扩展; 4 简单地建立了对象的初始容量。如果你放 2,它也会起作用。
    • 好的,所以你可以使用init?
    • 由于 NSMutableArray 类继承自 NSArray,看来可以。我只是没有看到它在 NSMutableArray 中使用。一直都是-initWithCapacity。
    • 好吧,我总是使用简单的旧init。只是想看看有没有什么特别之处。
    猜你喜欢
    • 2014-05-22
    • 1970-01-01
    • 2011-06-01
    • 2012-10-02
    • 2014-07-11
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多