您的位置:首页 > 移动开发 > Swift

swift UIView常用添加方法

2015-11-09 12:16 567 查看
Swift 添加UIView有几种常见方法

[objc] view
plaincopy

func insertSubview(view: UIView, atIndex index: Int)  

func addSubview(view: UIView)  

func insertSubview(view: UIView, belowSubview siblingSubview: UIView)  

func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)  

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

[objc] view
plaincopy

let view1=UIView(frame: CGRectMake(10, 50, 200, 200))  

let view2=UIView(frame: CGRectMake(170, 210, 200, 200))  

view1.backgroundColor=UIColor.redColor()  

view2.backgroundColor=UIColor.greenColor()  

  

self.view.addSubview(view1)  

self.view.addSubview(view2)  

我们看下效果



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

[objc] view
plaincopy

var arr:[AnyObject]  

arr = self.view.subviews;  

println("arr=%d",arr.count)  

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

下来我们看下这个方法

insertSubview(view: UIView, atIndex index: Int)

将view添加上来

[objc] view
plaincopy

let blueView=UIView(frame: CGRectMake(90, 130, 200, 200))  

blueView.backgroundColor=UIColor.blueColor()  

self.view.insertSubview(blueView, atIndex: 3)  

效果如下



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

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

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

[objc] view
plaincopy

func insertSubview(view: UIView, belowSubview siblingSubview: UIView)  

func insertSubview(view: UIView, aboveSubview siblingSubview: UIView)  

[objc] view
plaincopy

let orangeView=UIView(frame: CGRectMake(50, 90, 200, 200))  

orangeView.backgroundColor=UIColor.orangeColor()  

self.view.insertSubview(orangeView, belowSubview: blueView)  

  

let purpleView=UIView(frame: CGRectMake(130, 170, 200, 200))  

purpleView.backgroundColor=UIColor.purpleColor()  

self.view.insertSubview(purpleView, aboveSubview: blueView)  

效果如下



我们看到他是讲新的两个view分别添加打了 blueview的上边和下边
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: