有没有办法获得外部屏幕边框和条形按钮项之间的距离。我在考虑类似于如何获得状态栏高度的东西?
(我问这个,因为根据设备的不同而不同。)
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坐标一起工作..
答案 0 :(得分:2)
在外屏幕上,我假设你在谈论主窗口。
您可以尝试将条形按钮的框架转换为窗口的坐标,以便找到每个方向的距离:
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))
但是,主窗口接收旋转事件并将它们传递给控制器,这意味着它不会改变其帧大小,因此上述解决方案将无法在横向模式下正常工作。
您可以尝试将按钮的矩形转换为根视图控制器的坐标系,但现在您必须考虑状态栏的高度:
let frame = buttonItemView.superview!.convertRect(buttonItemView.frame, toView: UIApplication.sharedApplication().keyWindow?.rootViewController?.view)
答案 1 :(得分:0)
解决了这段代码:
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()
来获取绝对值。您现在有一个与条形按钮项目大小完全相同的标签!
答案 2 :(得分:-1)
UIApplication.sharedApplication().statusBarFrame.height