我需要显示一个包含3个元素的工具栏(两侧各有两个按钮,中间有一个标签)。它们中的每一个都是使用自定义UIButton创建的。这是代码:
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.sizeToFit()
let titleButton = UIButton(type: .custom)
titleButton.titleLabel?.numberOfLines = 0
titleButton.setTitle(self.toolBarLabelString, for: UIControlState.normal)
titleButton.setTitleColor(.darkGray, for: .normal)
titleButton.frame = CGRect.init(x: 0, y: 0, width: self.view.frame.width - 180, height: 40)
titleButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20.0, bottom: 0, right: -14.0)
//titleButton.backgroundColor = .yellow
let doneButton = UIButton(type: .custom)
doneButton.setTitle("Done", for: UIControlState.normal)
doneButton.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40)
doneButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0.0, bottom: 0, right: -24.0)
doneButton.setTitleColor(.green, for: .normal)
doneButton.addTarget(self, action: #selector(CreateRecipeViewController.donePicker), for: .touchUpInside)
//doneButton.backgroundColor = .yellow
let cancelButton = UIButton(type: .custom)
cancelButton.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40)
cancelButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: -14.0, bottom: 0, right: 0)
cancelButton.setTitle("Cancel", for: UIControlState.normal)
cancelButton.setTitleColor(.red, for: .normal)
cancelButton.addTarget(self, action: #selector(CreateRecipeViewController.cancelPicker), for: .touchUpInside)
let titleBarButton = UIBarButtonItem(customView: titleButton)
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
spaceButton.width = 20
let cancelBarButton = UIBarButtonItem(customView: cancelButton)
//let cancelBarButton = UIBarButtonItem(barButtonSystemItem : .cancel, target: nil, action: #selector(CreateRecipeViewController.cancelPicker))
//let doneBarButton = UIBarButtonItem(barButtonSystemItem : .done, target: nil, action: #selector(CreateRecipeViewController.donePicker))
let doneBarButton = UIBarButtonItem(customView: doneButton)
toolBar.setItems([cancelBarButton, spaceButton, titleBarButton, spaceButton, doneBarButton], animated: false)
toolBar.isUserInteractionEnabled = true
我看到两侧的按钮没有显示,因为它们与中心元素重叠。我尝试设置一个框架和contenEdgeInsets,但这没有帮助。
我将非常感谢您的任何帮助/想法。
谢谢!