屏幕边框和条形按钮项目之间的距离

Distance between screen border and bar button item

有没有办法获取外屏幕边框和栏按钮项之间的距离。我在想类似的东西,比如如何获取状态栏高度?

(我问这个,因为它因设备而异。)

这是一些试用代码:

    let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, view.frame.size.width, 64))
    let navigationBar.backgroundColor = UIColor.redColor()

    let barButtonItem = UIBarButtonItem(barButtonSystemItem: .Camera, target: self, action: nil)
    navigationItem.leftBarButtonItem = barButtonItem
    navigationBar.items = [navigationItem]

    let buttonItemView = barButtonItem.valueForKey("view") as! UIView
    let frame = buttonItemView.superview!.convertRect(buttonItemView.frame, toView: UIApplication.sharedApplication().keyWindow?.rootViewController?.view)
    let xCoordinateMin = CGRectGetMinX(frame)
    let yCoordinateMax = CGRectGetMaxY(frame)
    let yCoordinateMin = CGRectGetMinY(frame)

    let label = UILabel(frame: CGRectMake(CGFloat(xCoordinateMin), CGFloat(yCoordinateMin), 100, yCoordinateMax - yCoordinateMin))
    label.backgroundColor = UIColor.greenColor()

但它仍然给我 0 作为 xMin,尽管它似乎适用于 y 坐标..

UIApplication.sharedApplication().statusBarFrame.height

外屏,我猜你说的是主屏window。

您可以尝试将条形按钮的框架转换为 window 的坐标,以便找到到每个方向的距离:

let buttonItemView = barButtonItem.valueForKey("view") as! UIView
let frame = buttonItemView.superview!.convertRect(buttonItemView.frame, toView: nil)

print("Distance to left: ", CGRectGetMinX(frame))
print("Distance to top: ", CGRectGetMinY(frame))

但是,main window 接收旋转事件并将它们传递给控制器​​,这意味着它不会更改其帧大小,因此上述解决方案无法在横向模式下正常工作。

您可以尝试将按钮的矩形转换为根视图控制器的坐标系,但现在您必须考虑状态栏高度:

let frame = buttonItemView.superview!.convertRect(buttonItemView.frame, toView: UIApplication.sharedApplication().keyWindow?.rootViewController?.view)

使用此代码解决:

    let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, view.frame.size.width, 124))
    navigationBar.backgroundColor = UIColor.redColor()

    let barButtonItem = UIBarButtonItem(barButtonSystemItem: .Camera, target: self, action: nil)
    navigationItem.leftBarButtonItem = barButtonItem
    navigationBar.items = [navigationItem]

    let buttonItemView = barButtonItem.valueForKey("view") as! UIView
    let frame = buttonItemView.superview!.convertRect(buttonItemView.frame, toView: nil)
    let xCoordinateMin: CGFloat = CGRectGetMinX(frame)
    let xCoordinateMax: CGFloat = CGRectGetMaxX(frame)
    let yCoordinateMax: CGFloat = CGRectGetMaxY(frame)
    let yCoordinateMin = CGRectGetMinY(frame)

    let label = UILabel(frame: CGRectMake(abs(xCoordinateMin), yCoordinateMin, xCoordinateMax - xCoordinateMin, yCoordinateMax - yCoordinateMin))
    label.backgroundColor = UIColor.greenColor()

诀窍是将 let xCoordinateMin 声明为 CGFloat 因为那样它被认为是负值。然后在创建标签时只需使用 abs() 来获取绝对值。您现在有一个与您的条形按钮项目大小完全相同的标签!