如何在Swift中相对于UIWindow获取UIBarButtonItem的框架?

时间:2018-10-09 11:05:10

标签: ios swift uinavigationbar uibarbuttonitem uiwindow

关于这个主题,我已经浏览了很多SO帖子。但是我有不同的要求。

我正在我的应用程序中的应用演练页面上工作,我想针对某些UI对象显示一些提示。我想将UIView放在整个页面上方以使其模糊,然后显示突出显示的图像和提示文本。因此,我需要相对于UIWindow的那些对象的框架(需要帮助),以便我可以在它们的正上方放置另一个突出显示的图像。我已经用以下代码在tableview的标题内找到了几个对象的框架。

//Hint for expand/collapse arrow
guard let deviceHeaderView: StatusSectionView = tblStatus.headerView(forSection: 0) as? StatusSectionView else {
    //Hide expand/collapse hint objects
}

if let imgExpandCollapseFrame = deviceHeaderView.imgExpandCollapse.superview?.convert(deviceHeaderView.imgExpandCollapse.frame, to: window) {
    print("Frame of imgExpandCollapse.. \(imgExpandCollapseFrame)")

    let xPosition = (imgExpandCollapseFrame.origin.x + (imgExpandCollapseFrame.size.width/2)) - appWalkthroughView.downArrowHintImgView.frame.size.width/2

    let yPosition = (imgExpandCollapseFrame.origin.y + (imgExpandCollapseFrame.size.height/2)) - appWalkthroughView.downArrowHintImgView.frame.size.height/2

    appWalkthroughView.downArrowHintImgView.frame = CGRect(x: xPosition,
                                                           y: yPosition,
                                                           width: appWalkthroughView.downArrowHintImgView.frame.size.width,
                                                           height: appWalkthroughView.downArrowHintImgView.frame.size.height)
}

类似地,我需要找到UIBarButtonItem的框架,并相对于UIWindow转换其框架,并在其上方显示提示图像。

为此,我发现了UIBarButtonItem的框架,

let leftBarButtonItem = self.navigationItem.leftBarButtonItem!

if let leftBarButtonItemView = leftBarButtonItem.value(forKey: "view") as? UIView {
    print(leftBarButtonItemView.frame)
}

这段代码仅给出了条形按钮项的边界。

(0.0, 0.0, 36.0, 44.0)

而且我无法相对于UIWindow转换其框架。我们如何实现这一目标?

2 个答案:

答案 0 :(得分:0)

您可以要求视图为您进行转换:

let frameInWindow = leftBarButtonItemView.convert(leftBarButtonItemView.bounds, to: nil)

(转换将使用寡妇的坐标系,因为目标视图为零)

答案 1 :(得分:0)

let leftBarButtonItem = self.navigationItem.leftBarButtonItem
        if let leftBarButtonItemView = leftBarButtonItem?.value(forKey: "view") as? UIView {
            //You should ask your window to convert your frame to his frames.
            if let rect = UIApplication.shared.keyWindow?.convert(leftBarButtonItemView.frame, from: nil) {

            }
        }