带模板图像的UIButton仅接收非透明像素的触摸事件

时间:2015-11-05 23:05:25

标签: ios swift uibutton

我有一个用Swift(2.1)编写的iOS应用程序。我正在使用一些解决方法,我发现它在NavigationBar中的UIBarButtonItem之间产生较小的边距。这是我的代码:

    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上使用Tap Gesture Recognizer的解决方案,但是按钮没有悬停,所以它不是最好的解决方案。

使用setImage而不是setBackgroundImage不会改变任何东西。创建类型为UIButtonType.Custom的按钮也是如此。

帮助!

1 个答案:

答案 0 :(得分:0)

想出来!我的理论错了。这不是因为透明像素。问题导致这一行:

(svg.node().getBBox().width / 2) - scale * g.getBBox().x)

这导致按钮偏移了10个点,而不是在其容器的中心。按钮看起来很好看,但是当我将背景设置为modeButtonContainer时,我意识到按钮仅在容器区域工作,并且在外面不起作用。

所以我需要删除这一行,而是使用add this作为rightBarButtonItems中的第一项:

(function(){

 var svg, g; $.get('http://layersofcomplexity.com/__fp.svg', function(svg){
   $('body').append($(svg));
   init();
  },'text');

  function init() {

    console.log('init');

   svg = d3.select('svg');
   g = d3.select('svg > g');

    var zoom = d3.behavior.zoom()
    .translate([0, 0])
    .scale(1)
    .scaleExtent([1, 8])
    .on("zoom", zoomed);

    svg
    .call(zoom)
    .call(zoom.event);

    $('.pan').on('click', function(){
//       var id = '#g-1011';
      var scale = 4;
      var bbox = $('#g-1101')[0].getBBox(); 
//       d3.select(id).node().getBBox();
      var x = bbox.x;
      var y = bbox.y;
      // var scale = .9 / Math.max(dx / width, dy / height),
      // var translate = [width / 2 - scale * x, height / 2 - scale * y];
      var width = svg.node().getBBox().width;
      var height = svg.node().getBBox().height;
      var translate = [-scale*x,-scale*y];
      g.transition().duration(750) .call(zoom.translate(translate).scale(scale).event);
    });

  }

  function zoomed() {
    g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

})();