6

我正在尝试将UIView带有“完成”的按钮作为输入附件视图添加到文本字段。

        let view = UIView()
        let doneButton = UIButton(type: .Custom)
        doneButton.setTitle("Done", forState: .Normal)
        doneButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(doneButton)
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[button]-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["button":doneButton]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button]|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["button":doneButton]))
        view.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: doneButton, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0)) // Even this does not work
        self.emailTextField.inputAccessoryView = view

但是,我看不到正在设置的视图高度,也看不到 Xcode 中的 View Hierarchy 调试器/检查器中的按钮。

但是如果我通过设置它的框架来添加一个视图,我可以看到正在添加的视图。我也尝试将高度约束强行设置为常数 21,它打破了一些我没有添加的其他约束_UIKBAutolayoutHeightConstraint

"<NSLayoutConstraint:0x7fa3c962be50 UIView:0x7fa3c963bf60.height == UIButton:0x7fa3c963c0d0.height + 21>",
    "<NSLayoutConstraint:0x7fa3c95e0a90 '_UIKBAutolayoutHeightConstraint' V:[UIView:0x7fa3c963bf60(0)]>"

以前有人遇到过这个问题吗?

4

1 回答 1

-2

斯威夫特 3+

  1. 您需要在第一行指定工具栏视图的大小。
  2. 不要在 viewcontroller 类中使用“view”作为变量,因为它会与 self.view 产生混淆

    override func viewDidLoad() {
        super.viewDidLoad()
        let toolBar = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 50))
        toolBar.backgroundColor = .gray
        let doneButton = UIButton(type: .custom)
        doneButton.setTitle("Done", for: .normal)
        doneButton.translatesAutoresizingMaskIntoConstraints = false
        toolBar.addSubview(doneButton)
        toolBar.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[button]-|", 
                                                              options: .directionLeadingToTrailing, 
                                                              metrics: nil, 
                                                              views: ["button":doneButton]))
        toolBar.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[button]|", 
                                                              options: .directionLeadingToTrailing, 
                                                              metrics: nil, 
                                                              views: ["button":doneButton]))
        self.emailTextField.inputAccessoryView = toolBar 
    }
    
于 2017-10-02T04:00:02.653 回答