将标签的 center.x 与 tabBar 的 imageView 内的图像对齐

Align label's center.x with image inside tabBar's imageView

我需要让标签的 center.x 直接与 tabBar 的 imageView 中的图像对齐。使用下面的代码,标签未对齐,而不是标签的文本“123”直接位于 tabBar 内的铃铛上方,而是偏向右侧。

guard let keyWindow = UIApplication.shared.windows.first(where: { [=11=].isKeyWindow }) else { return }

guard let fourthTab = tabBarController?.tabBar.items?[3].value(forKey: "view") as? UIView else { return }

guard let imageView = fourthTab.subviews.compactMap({ [=11=] as? UIImageView }).first else { return }

guard let imageViewRectInWindow = imageView.superview?.superview?.convert(fourthTab.frame, to: keyWindow) else { return }

let imageRect = AVMakeRect(aspectRatio: imageView.image!.size, insideRect: imageViewRectInWindow)

myLabel.text = "123"
myLabel.textAlignment = .center // I also tried .left
myLabel.center.x = imageRect.midX
myLabel.center.y = UIScreen.main.bounds.height - 74
myLabel.frame.size.width = 50
myLabel.frame.size.height = 21

print("imageViewRectInWindow: \(imageViewRectInWindow)") // (249.99999999403948, 688.0, 79.00000000298022, 48.0)
print("imageRect: \(imageRect)") // (265.4999999955296, 688.0, 48.0, 48.0)
print("myLabelRect: \(myLabel.frame)") // (289.4999999955296, 662.0, 50.0, 21.0)

这可能是布局问题,例如,在布局所有内容之前设置坐标。你从哪里调用代码?我能够让它与以下一起工作,但是如果你使用的功能,一些会得到奇怪的结果,所以删掉其中的几个。使用 tabview 的框架对我有用,并从视图控制器的 viewDidLayoutSubviews 函数调用坐标设置。

class ViewController: UIViewController {

    var myLabel: UILabel = UILabel()

    var secondTab: UIView?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.view.addSubview(myLabel)
        myLabel.textColor = .black
        myLabel.text = "123"
        myLabel.textAlignment = .center // I also tried .left
        myLabel.frame.size.width = 50
        myLabel.frame.size.height = 21

        secondTab = tabBarController?.tabBar.items?[1].value(forKey: "view") as? UIView
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        guard let secondTab = secondTab else {
            return
        }

        myLabel.center.x = secondTab.frame.midX
        myLabel.center.y = UIScreen.main.bounds.height - 70
    }
}

尝试使用下面的代码 return tabbar 项目索引的 centreX。

extension UIViewController {

    func centerX(of tabItemIndex: Int) -> CGFloat? {
        guard let tabBarItemCount = tabBarController?.tabBar.items?.count else { return nil }
        let itemWidth = view.bounds.width / CGFloat(tabBarItemCount)
        return itemWidth * CGFloat(tabItemIndex + 1) - itemWidth / 2
    }
}