首页 > 解决方案 > 除非有背景颜色,否则 UIButton 不会更改图像

问题描述

这很奇怪,我尝试了 UIControl.State() 的不同排列。除非我为图像添加背景颜色,否则实际图像不会改变。

func followUserLocation {
    let button = UIButton(type: UIButton.ButtonType.custom)
    button.frame = CGRect(x: 10, y: 500, width: 50, height: 50)
    
    if followUserStatus {
      followUserButton = UIImage(named: "follow_user_high")
      button.setImage(followUserButton, for: .normal)
      let coordinateRegion = MKCoordinateRegion(center: coordinatesToAppend, latitudinalMeters: 2500, longitudinalMeters: 2500)
      vcTrainMapView.setRegion(coordinateRegion, animated: true)
      print("0 AA - TRUE \(followUserButton) \(UIControl.State())")
    } else {
      followUserButton = (UIImage(named: "follow_user"))
      button.setImage(followUserButton, for:.selected)
      print("0 BB- FALSE \(followUserButton) \(UIControl.State())")
    }

    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

//    button.backgroundColor = .lightGray // Once I utilise this, it works.
    self.view.addSubview(button)
  }

这是打印输出。UIControl.State() 在按下时也不会改变。

0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)
0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)
0 BB- FALSE Optional(<UIImage:0x600001504a20 named(main: follow_user) {40, 40}>) UIControlState(rawValue: 0)
0 BB- FALSE Optional(<UIImage:0x600001504a20 named(main: follow_user) {40, 40}>) UIControlState(rawValue: 0)
0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)
0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)
0 AA - TRUE Optional(<UIImage:0x60000154b0f0 named(main: follow_user_high) {40, 40}>) UIControlState(rawValue: 0)

标签: swiftuibutton

解决方案


我认为您应该删除 if 语句,然后将按钮图像设置为.normal.selected状态。之后,更新按钮选择状态。

func followUserLocation {
    let button = UIButton(type: UIButton.ButtonType.custom)
    button.frame = CGRect(x: 10, y: 500, width: 50, height: 50)

    followUserButton = UIImage(named: "follow_user_high")
    button.setImage(followUserButton, for:.selected)

    followUserButton = (UIImage(named: "follow_user"))
    button.setImage(followUserButton, for: .normal)

    if followUserStatus {
      let coordinateRegion = MKCoordinateRegion(center: coordinatesToAppend, latitudinalMeters: 2500, longitudinalMeters: 2500)
      vcTrainMapView.setRegion(coordinateRegion, animated: true)
    }

    button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
    self.view.addSubview(button)
  }

@objc private func buttonAction(_ sender: UIButton) {
    sender.isSelected.toggle()
    print(sender.isSelected)
}

推荐阅读