iOS UI系列 (四) :可复用的Xib(1) 静态内容

有时候页面中的部分内容相同,或者是一些静态的内容组合,这时候我们就可以把这些见面封装到一个XIB里

新建Single View Application

新建一个View.Xib

  1. Command+N–>User Interface–>View
  2. 把界面大小改为Freeform
  3. 添加一个UILabel, 两个UIView, 并设置对应的背景色
  4. 添加对应的约束,让两个UIView等宽,且Space都是10, 高度固定,且与周围的约速为10, 对UILabel也设置对应的约速,细节就不写了,看图

使用Xib

在ViewController添加 一个UIView, 并设置对应的约束,连接这个UIView为Controller的 IBOutlet ContainerView

  1. 在ViewDidLoad里添加如下代码
1
2
3
4
5
6
7
super.viewDidLoad()

let arr = NSBundle.mainBundle().loadNibNamed("View", owner: nil, options: nil)

let v = arr[0] as! UIView

containerView.addSubview(v)

运行

  1. 添加约束
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import UIKit

class ViewController: UIViewController {

@IBOutlet weak var containerView: UIView!

var v: UIView!

override func viewDidLoad() {

super.viewDidLoad()

let arr = NSBundle.mainBundle().loadNibNamed("View", owner: nil, options: nil)
v = arr[0] as! UIView


​ containerView.addSubview(v)

1
setUpConstraint()


​ // Do any additional setup after loading the view, typically from a nib.
​ }

1
2
3
4
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 func setUpConstraint()
{

v.setTranslatesAutoresizingMaskIntoConstraints(false)

containerView.addConstraint(NSLayoutConstraint(
item:v, attribute:.Leading,
relatedBy:.Equal, toItem:containerView,
attribute:.Left, multiplier:1, constant:0))

containerView.addConstraint(NSLayoutConstraint(
item:v, attribute:.Trailing,
relatedBy:.Equal, toItem:containerView,
attribute:.Right, multiplier:1, constant:0))

containerView.addConstraint(NSLayoutConstraint(
item:v, attribute:.Top,
relatedBy:.Equal, toItem:containerView,
attribute:.Top, multiplier:1, constant:0))

containerView.addConstraint(NSLayoutConstraint(
item:v, attribute:.Bottom,
relatedBy:.Equal, toItem:containerView,
attribute:.Bottom, multiplier:1, constant:0))

}

}


3. 运行结果, 我们的Xib已经可以自适应容器了


Author

王德水

Posted on

2015-07-28

Updated on

2021-01-05

Licensed under

版权:本文版权归作者所有,转载需经作者同意。

Comments