我使用旧方法将UIView
注入到UIViewController
中,但是升级到iOS 12后,它将无法正常工作,错误是:
libc++abi.dylib: terminating with uncaught exception of type NSException
这是代码
class SlideOutMenu: UIViewController {
var contentView:UIView!
func setContentViewIn(view: UIView) {
self.contentView = view
self.view.addSubview(self.contentView)
}
}
然后
class MainController: UIViewController {
var slide = SlideOutMenu()
var viewToAdd = ViewToAdd() // extends UIView
override func viewDidLoad()
{
super.viewDidLoad()
slide.setContentViewIn(viewToAdd)
}
}
它不起作用,但是如果我这样声明,它就会起作用
class SlideOutMenu: UIViewController {
var contentView:UIView!
convenience init(childView: UIView) {
self.init(nibName:nil, bundle:nil)
self.contentView = childView
}
override func viewDidLoad() {
view.addSubview(self.contentView)
}
}
并使用
SlideOutMenu(childView: UIView())
有效。
但是这样,事实并非如此。太奇怪了
SlideOutMenu(childView: viewToAdd)
答案 0 :(得分:-2)
此在iOS 12中运行的以下代码已选中* 导入UIKit
ViewController类:UIViewController {
var view1 : UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view1 = UIView.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view1.center = self.view.center
view1.backgroundColor = .red
self.view.addSubview(self.view1)
}
} *
答案 1 :(得分:-2)
以下是我如何以编程方式构建视图的示例:
class InformationController: UIViewController {
let labelDescription: UILabel = {
let label = UILabel()
label.text = "Label Name"
// this is important for auto layout to work
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
private func setupView() {
// add the view
view.addSubview(labelDescription)
// set the auto layout and enable the constraints
labelDescription.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
labelDescription.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10).isActive = true
labelDescription.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
labelDescription.heightAnchor.constraint(equalToConstant: 25).isActive = true
}
}