UIViewController
中的问题是rightBarButtonItem
没有垂直对齐。我想将按钮向下移动10个像素。
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(didPressCancelButton))
navigationItem.setRightBarButton(cancelButton, animated: true)
navigationItem.rightBarButtonItem?.setBackgroundVerticalPositionAdjustment(12, for: .default) navigationItem.rightBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: 12), for: .default)
我也尝试在viewDidLayoutSubviews()
中移动代码,但无所事事。
当前配置: iOS 11
答案 0 :(得分:0)
您可以使用自定义视图创建UIBarButtonItem。这个自定义视图将是一个UIView,其实际UIButton(作为子视图)从顶部放置x像素(x =您要将其向下移动的像素数)。
以下是如何执行此操作的示例:
var button = UIButton(type: .custom)
button.setTitle("Settings", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
button.setTitleColor(UIColor(red: 179.0 / 255.0, green: 40.0 / 255.0, blue: 18.0 / 255.0, alpha: 1), for: .normal)
button.frame = CGRect(x: 0, y: 0, width: 50, height: 20)
button.addTarget(self, action: #selector(self.yourCustomSelectorHere), for: .touchUpInside)
var backButtonView = UIView(frame: CGRect(x: 0, y: 0, width: 63, height: 33))
backButtonView.bounds = backButtonView.bounds.offsetBy(dx: -14, dy: -7)
backButtonView.addSubview(button)
var barBtnItem = UIBarButtonItem(customView: backButtonView)
navigationItem?.rightBarButtonItem = barBtnItem
您只需稍微配置代码即可在视图中的正确位置。