【发布时间】:2020-03-13 03:57:39
【问题描述】:
我在我的 iOS 应用程序上创建了一个 UITabBarController 的子类,因为我想在标签栏上添加一个中间的“+”按钮。我使用下面的代码添加了这个额外的按钮:
class XGTabBarViewController: UITabBarController {
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 70, height: 70))
private let optionMenu = UIAlertController(title: nil, message: "New", preferredStyle: .actionSheet)
override func viewDidLoad() {
super.viewDidLoad()
let action1 = UIAlertAction(title: "Action 1", style: .default)
let action2 = UIAlertAction(title: "Action 2", style: .default)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
optionMenu.addAction(action1)
optionMenu.addAction(action2)
optionMenu.addAction(cancelAction)
var menuButtonFrame = menuButton.frame
let iconConfig = UIImage.SymbolConfiguration(pointSize: 24, weight: .medium, scale: .medium)
let iconImage = UIImage(systemName: "plus", withConfiguration: iconConfig)
let icon = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
icon.image = iconImage
icon.tintColor = UIColor.white
menuButtonFrame.origin.y = view.bounds.height - menuButtonFrame.height - 50
menuButtonFrame.origin.x = view.bounds.width/2 - menuButtonFrame.size.width/2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = UIColor(named: "LinkBlue")
menuButton.layer.cornerRadius = menuButtonFrame.height/2
menuButton.layer.shadowColor = UIColor.black.cgColor
menuButton.layer.shadowRadius = 3
menuButton.layer.shadowOpacity = 0.3
menuButton.layer.shadowOffset = CGSize(width: 0, height: 3)
menuButton.addSubview(icon)
icon.translatesAutoresizingMaskIntoConstraints = false
icon.widthAnchor.constraint(equalToConstant: 30).isActive = true
icon.heightAnchor.constraint(equalToConstant: 30).isActive = true
icon.centerXAnchor.constraint(equalTo: menuButton.centerXAnchor).isActive = true
icon.centerYAnchor.constraint(equalTo: menuButton.centerYAnchor).isActive = true
view.addSubview(menuButton)
menuButton.addTarget(self, action: #selector(menuButtonAction(sender:)), for: .touchUpInside)
view.layoutIfNeeded()
}
@objc private func menuButtonAction(sender: UIButton) {
self.present(optionMenu, animated: true, completion: nil)
}
我通过 IB 设置标签栏控制器。这就是它的样子
那么,我想知道是否应该在此类中定义菜单按钮操作?还是有更好的(最佳实践)方法来做到这一点?
如您所见,我尝试添加一个在点击按钮时将显示的操作表。但是我遇到了一些布局错误。我想知道我是否在正确的位置添加了此代码。
我收到以下错误:
谢谢!
【问题讨论】:
-
你的约束被打破了......但你把代码放在了正确的地方
-
而不是 view.addSubview ... 做 tabBar.addSubview(button)
-
我这样做了,但是按钮不再显示了。
-
@CrisDenopol 请在我认为可行的前 -37 值中设置图像插图。