我正在编写自定义键盘,我想自定义高度。苹果文档只在Objective-C中给出了该代码,有人知道如何用Swift语言编写它吗?这是来自苹果的代码:
CGFloat _expandedHeight = 500;
NSLayoutConstraint *_heightConstraint =
[NSLayoutConstraint constraintWithItem: self.view
attribute: NSLayoutAttributeHeight
relatedBy: NSLayoutRelationEqual
toItem: nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier: 0.0
constant: _expandedHeight];
[self.view addConstraint: _heightConstraint];
我试着这样写,但它什么也没做..:
override func viewDidAppear(animated:Bool) {
super.viewDidAppear(true)
let nib = UINib(nibName: "KeyboardView", bundle: nil)
let objects = nib.instantiateWithOwner(self, options: nil)
view = objects[0] as UIView;
let _viewHeight: CGFloat = 256
let const1 = NSLayoutConstraint(
item:self.view, attribute:.Height,
relatedBy:.Equal, toItem:nil,
attribute:.NotAnAttribute,multiplier:0, constant: _viewHeight)
view.addConstraint(const1)
}
请帮帮我!
你有一个multiplier:0
,它应该是multiplier:1.0
。
您也可以混合self.view
和view = objects[0] as UIView
。您应该向主self.view
添加一个约束,即 = self.inputView
并在其上添加自定义视图。
let customView = objects[0] as UIView
customView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubView(customView)
//layout
let left = NSLayoutConstraint(item: customView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant: 0.0)
let top = NSLayoutConstraint(item: customView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0)
let right = NSLayoutConstraint(item: customView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1.0, constant: 0.0)
let bottom = NSLayoutConstraint(item: customView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
self.view.addConstraints([left, top, right, bottom])
let const1 = NSLayoutConstraint(
item:self.view, attribute:.Height,
relatedBy:.Equal, toItem:nil,
attribute:.NotAnAttribute,multiplier:1.0, constant: _viewHeight)
self.view.addConstraint(const1)