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 最常见就是普通的添加
let view1=UIView(frame: CGRectMake(10,50,200,200)) let view2=UIView(frame: CGRectMake(170,210,200)) view1.backgroundColor=UIColor.redColor() view2.backgroundColor=UIColor.greenColor() self.view.addSubview(view1) self.view.addSubview(view2)我们看下效果
解析来我们获取一下 self.view的子视图,然后就知道刚才添加的两个视图的index
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添加上来
let blueView=UIView(frame: CGRectMake(90,130,200)) blueView.backgroundColor=UIColor.blueColor() self.view.insertSubview(blueView,atIndex: 3)
效果如下
我们可以看到 blueView添加到了view1和view2之间了
下来我们两个方法一起比较来看
func insertSubview(view: UIView,aboveSubview siblingSubview: UIView)
let orangeView=UIView(frame: CGRectMake(50,90,200)) orangeView.backgroundColor=UIColor.orangeColor() self.view.insertSubview(orangeView,belowSubview: blueView) let purpleView=UIView(frame: CGRectMake(130,170,200)) purpleView.backgroundColor=UIColor.purpleColor() self.view.insertSubview(purpleView,aboveSubview: blueView)
效果如下
我们看到他是讲新的两个view分别添加打了 blueview的上边和下边
好了,大家再研究一下
苹果开发群 :414319235 欢迎加入 欢迎讨论问题
原文链接:https://www.f2er.com/swift/326106.html