swift UIView常用添加方法

Swift 添加UIView有几种常见方法

[objc]  view plain copy
  1. func insertSubview(view: UIView, atIndex index: Int)  
  2. func addSubview(view: UIView)  
  3. func insertSubview(view: UIView, belowSubview siblingSubview: UIView)  
  4. func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)  


首先 addSubview 最常见就是普通的添加

[objc]  view plain copy
  1. let view1=UIView(frame: CGRectMake(1050200200))  
  2. let view2=UIView(frame: CGRectMake(170210200200))  
  3. view1.backgroundColor=UIColor.redColor()  
  4. view2.backgroundColor=UIColor.greenColor()  
  5.   
  6. self.view.addSubview(view1)  
  7. self.view.addSubview(view2)  
我们看下效果




解析来我们获取一下 self.view的子视图,然后就知道刚才添加的两个视图的index

[objc]  view plain copy
  1. var arr:[AnyObject]  
  2. arr = self.view.subviews;  
  3. println("arr=%d",arr.count)  

结果为4,那么view1 index为2,view2的index为3



下来我们看下这个方法

insertSubview(view: UIView, atIndex index: Int)

将view添加上来

[objc]  view plain copy
  1. let blueView=UIView(frame: CGRectMake(90130200200))  
  2. blueView.backgroundColor=UIColor.blueColor()  
  3. self.view.insertSubview(blueView, atIndex3)  

效果如下

我们可以看到 blueView添加到了view1和view2之间了

所有说 这个方法就是将view添加到指定位置



下来我们两个方法一起比较来看

[objc]  view plain copy
  1. func insertSubview(view: UIView, belowSubview siblingSubview: UIView)  
  2. func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)  

[objc]  view plain copy
  1. let orangeView=UIView(frame: CGRectMake(5090200200))  
  2. orangeView.backgroundColor=UIColor.orangeColor()  
  3. self.view.insertSubview(orangeView, belowSubview: blueView)  
  4.   
  5. let purpleView=UIView(frame: CGRectMake(130170200200))  
  6. purpleView.backgroundColor=UIColor.purpleColor()  
  7. self.view.insertSubview(purpleView, aboveSubview: blueView)  

效果如下


我们看到他是讲新的两个view分别添加打了 blueview的上边和下边

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值