我有一个用Swift(2.1)编写的iOS应用程序。我正在使用一个小的变通方法,我发现在导航栏中的uibarbuttonem之间的边距更小。这是我的代码:

    let modeImage = UIImage(named: modeFilename)!.imageWithRenderingMode(.AlwaysTemplate)
    modeButton = UIButton(frame: CGRectMake(0, 0, 22, 22))
    modeButton.setBackgroundImage(modeImage, forState: .Normal)
    modeButton.addTarget(self, action: Selector("modeClicked:"), forControlEvents:.TouchUpInside)
    modeButton.transform = CGAffineTransformMakeTranslation(10, 0)
    let modeButtonContainer = UIView(frame: modeButton.frame)
    modeButtonContainer.addSubview(modeButton)
    modeButtonItem = UIBarButtonItem(customView: modeButtonContainer)

按钮工作,但我有一个正方形的简单图像和触摸只是工作在非透明像素(或附近可能)。在模拟器上很难找到,更不用说真正的设备了。真的很痛。我找到了在modeButtonContainer上使用轻触手势识别器的解决方案,但是按钮没有悬停,所以这不是最佳解决方案。
使用setImage而不是setBackgroundImage不会改变任何事情。创建类型为UIButtonType.Custom的按钮也是如此。
救命啊!

最佳答案

明白了!我的理论是错误的。这不是因为透明像素。问题导致此行:

modeButton.transform = CGAffineTransformMakeTranslation(10, 0)

这导致按钮偏移了10个点,而不是在其容器的中心。按钮看起来不错,但当我将背景设置为modeButtonContainer时,我意识到按钮只在容器区域工作,在容器区域之外不工作。
因此,我需要删除这一行,而使用add this作为rightbarbuttonems中的第一项:
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpacer.width = -10

关于ios - 带有模板图像的UIButton仅接收非透明像素的触摸事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33556496/

10-10 00:50