【发布时间】:2017-04-26 02:45:33
【问题描述】:
我被指示创建一个井字游戏。
要求是:
- 仅使用 MVC
- 以编程方式显示视图
- 仅使用约束设置正方形的大小
因此,我创建了一个 Board 类和一个 Square 类。板类几乎只是一个带有背景颜色的 UIView。我在初始化的主要问题。每次我使用自定义 UIView 时,我都必须使用 CGRect 框架进行初始化。讲师告诉我们不要直接使用 CGRect 函数设置视图的框架,而只能使用约束。
这就是问题所在。我正在尝试在另一个视图中初始化一个板。因为板子是 UIView 的子类,所以我必须设置一个框架。
如何在没有框架的情况下将 UIView 初始化为只能使用传入参数中的 UIView 的约束来设置它的 Size?
下面是我现在正在做的事情。我想在没有 frame 参数的情况下初始化它,但它是必需的。我想初始化这个类并在另一个视图控制器类的viewDidLoad 函数中使用它。我想传入一个 UIView 作为参数并根据该特定视图调整约束。
class Board: UIView {
init(frame: CGRect, view: UIView) {
super.init(frame: frame)
self.backgroundColor = .green
self.translatesAutoresizingMaskIntoConstraints = false
addConstraints(view: view)
}
func addConstraints(view:UIView){
NSLayoutConstraint(item: view,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leading,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: view,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailing,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: view,
attribute: .height,
relatedBy: .equal,
toItem: view,
attribute: .height,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: view,
attribute: .width,
relatedBy: .equal,
toItem: view,
attribute: .width,
multiplier: 1,
constant: 0).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
当我创建板类时,我想将约束设置为我在初始化类时作为参数传入的view。令人沮丧的是,它不会生效,因为我必须使用所需的帧初始化程序。
有没有办法解决这个问题?
【问题讨论】:
标签: ios swift cocoa-touch uiview nslayoutconstraint