【问题标题】:Make multiple buttons highlight when touch begins触摸开始时突出显示多个按钮
【发布时间】:2017-03-16 12:46:17
【问题描述】:

我在一个视图中放置了三个按钮,每个按钮都有不同的个人资料图片。当触摸开始对任何单个按钮进行触摸时,我需要所有三个按钮都突出显示,以便三个按钮一起看起来是一个按钮。我已经尝试了以下代码,但它不起作用。有什么想法吗?

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap))
    tapGesture.numberOfTapsRequired = 1
    friendsBtn1.addGestureRecognizer(tapGesture)

    func normalTap(sender: UITapGestureRecognizer){
        if sender.state == .began {
            friendsBtn2.isHighlighted = true
            friendsBtn3.isHighlighted = true
        }
        if sender.state == .ended {
            friendsBtn2.isHighlighted = false
            friendsBtn3.isHighlighted = false
        }
        print("Normal tap")
    }

【问题讨论】:

  • 你为friendsBtn2和friendsBtn3设置了高亮图像吗?
  • 结帐更新的答案。

标签: ios swift3 uibutton touchesbegan


【解决方案1】:

我认为不需要UITapGesture 你可以这样管理。 首先,您需要将突出显示的图像设置为按钮和设置按钮事件,如下所示。

override func viewDidLoad() {
        super.viewDidLoad()

        friendsBtn2.setImage(UIImage(named: "highlighted.png"), for: .highlighted)
        friendsBtn3.setImage(UIImage(named: "highlighted.png"), for: .highlighted)

        friendsBtn1.addTarget(self, action: #selector(YourViewController.touchDownEvent), for: .touchDown)
        friendsBtn1.addTarget(self, action: #selector(YourViewController.touchUpInsideEvent), for: .touchUpInside)
    }

之后在 ViewController 中添加方法 touchDownEvent(),touchUpInsideEvent()

func touchDownEvent() {
    self.allButtonHighlighted(fleg: true)
}

func touchUpInsideEvent() {
    self.allButtonHighlighted(fleg: false)
}

func allButtonHighlighted( fleg: Bool) {
    friendsBtn2.isHighlighted = fleg
    friendsBtn3.isHighlighted = fleg
}

我希望它会起作用。

【讨论】:

  • 我只是在 Xcode 8.2.1 中使用按钮的常规突出显示,而不是直接设置突出显示的图像。我确实尝试按照您所说的进行设置,但问题仍然是我的代码没有将其他按钮设置为突出显示。
  • 首先使用断点并检查您的代码“friendsBtn2.isHighlighted = true”是否执行?
【解决方案2】:

我确实解决了这个问题。这是代码。

[friendsBtn1, friendsBtn2, friendsBtn3].forEach { button in
        button?.addTarget(self, action:#selector(highlightAllButtons(sender:)), for: .touchDown)
        button?.addTarget(self, action:#selector(unhighlightAllButtons(sender:)), for: [.touchUpInside, .touchUpOutside])
    }

func highlightAllButtons(sender: UIButton) {
    [friendsBtn1, friendsBtn2, friendsBtn3].forEach { button in
        button.isHighlighted = true
    }
}
func unhighlightAllButtons(sender: UIButton) {
    [friendsBtn1, friendsBtn2, friendsBtn3].forEach { button in
        button.isHighlighted = false
    }
}

【讨论】:

    【解决方案3】:

    为按钮操作中的所有三个按钮尝试[button setSelected:YES];

    【讨论】:

      猜你喜欢
      • 2012-12-03
      • 2019-05-17
      • 2014-02-03
      • 2011-05-01
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      相关资源
      最近更新 更多