UIStackView 詳解 代碼實現

 /*
      //位置初始化
     - (instancetype)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER;
     //根據子視圖 初始化
    - (instancetype)initWithArrangedSubviews:(NSArray<__kindof UIView *> *)views; // Adds views as subviews of the receiver.
      //存放子視圖的數組
    @property(nonatomic,readonly,copy) NSArray<__kindof UIView *> *arrangedSubviews;
    //子視圖添加到UIStackView上的方法
    - (void)addArrangedSubview:(UIView *)view;
    //子視圖從列表中移除排列子視圖而不刪除它,若要刪除作爲子視圖視圖,將其發送-removeFromSuperview 像往常
    - (void)removeArrangedSubview:(UIView *)view;

      //如果它不是已經將視圖添加作爲容器的子視圖。
      更新的堆棧索引 (但不是子視圖索引)
      如果它已經在 arrangedSubviews 列表中,排列子視圖。
      
      - (void)insertArrangedSubview:(UIView *)view atIndex:(NSUInteger)stackIndex;
    //排列方式 
      UILayoutConstraintAxisHorizontal = 0,//水平
      UILayoutConstraintAxisVertical = 1//豎直
    @property(nonatomic) UILayoutConstraintAxis axis;
    
  //填充方式吧
    @property(nonatomic) UIStackViewDistribution distribution;
//對齊方式
    @property(nonatomic) UIStackViewAlignment alignment;
      //間隔
     @property(nonatomic) CGFloat spacing;
    @property(nonatomic,getter=isBaselineRelativeArrangement) BOOL baselineRelativeArrangement;
     @property(nonatomic,getter=isLayoutMarginsRelativeArrangement) BOOL layoutMarginsRelativeArrangement;
       */
    UIStackView * stackView =[[UIStackView alloc]initWithFrame:CGRectMake(0, 0, 220, 200)];
    /*
     Axis表示Stack View的subview是水平排布還是垂直排布。Alignment控制subview對齊方式。Distribution定義subview的分佈方式。Spacing 爲subview間的最小間距。
     */
    //豎直排列
    stackView.distribution = UIStackViewDistributionFillEqually ;
    
    stackView.axis =UILayoutConstraintAxisVertical;
    //對齊方式
    // stackView.alignment = UIStackViewAlignmentLeading;
    //添加到視圖上
    [self.view addSubview:stackView];
    /*
     subView和arrangedSubView
     
     開始使用Stack View前,我們先看一下它的屬性subViews和arrangedSubvies屬性的不同。如果你想添加一個subview給Stack View管理,你應該調用addArrangedSubview:或insertArrangedSubview:atIndex: arrangedSubviews數組是subviews屬性的子集。
     
     要移除Stack View管理的subview,需要調用removeArrangedSubview:和removeFromSuperview。移除arrangedSubview只是確保Stack View不再管理其約束,而非從視圖層次結構中刪除,理解這一點非常重要。
     */
    //創建控件
    UILabel * label1 =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
    label1.backgroundColor =[UIColor redColor];
    [stackView addArrangedSubview:label1];
    
    UILabel * label2 =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
    label2.backgroundColor =[UIColor greenColor];
    [stackView addArrangedSubview:label2];
    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章