【问题标题】:ios button shows image only when tappedios按钮仅在点击时显示图像
【发布时间】:2018-05-16 20:57:19
【问题描述】:

我有以下代码用于在我的按钮上设置图像:

button.setImage(UIImage(named: "X", in: getBundleForCommon(), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate), for: .normal)

但是图像只有在被点击然后消失时才会出现在按钮上。

如何在我的按钮上持续显示点击时不受影响的图像。

【问题讨论】:

  • 试试这行..Button.setBackgroundImage(pickedImage, for: .normal)
  • 已经尝试过 setBackgroundImage。没有帮助。
  • 您是否设置了除图像以外的按钮的任何属性?
  • @SharadChauhan,是的,也设置以下属性:Button.layer.cornerRadius = profilePicButton.frame.size.height / 2 Button.clipsToBounds = true Button.layer.borderWidth = 1.0 Button.layer.borderColor = VxColors.greyDark.color.cgColor -> 这些都生效了。只有在点击按钮时才能看到图像。

标签: ios swift


【解决方案1】:

试试这个,

button.setImage(UIImage(named:"x"), for: .normal)
button.setImage(UIImage(named:"x"), for: .highlighted)

【讨论】:

  • 你这边肯定有问题,删除按钮并从对象库拖新按钮
【解决方案2】:

使用 Swift 在 UIButton 上设置图像:

button.setImage(UIImage(named:"x"), for: .normal)

【讨论】:

    【解决方案3】:

    这行得通吗?

    button.setImage(UIImage(named: "X", in: getBundleForCommon(), compatibleWith: nil)?
    .withRenderingMode(.alwaysOriginal), for: .normal)
    

    【讨论】:

      【解决方案4】:

      尝试:

      for: UIControlState()
      

      而不是

      for: .normal
      

      【讨论】:

        【解决方案5】:

        您的图像是使用alwaysTemplate 创建的,这意味着颜色信息将被忽略。

        设置按钮tintColor,无需点击即可显示图片。

        let image = UIImage(named: "X", in: getBundleForCommon(), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
        button.setImage(image, for: .normal)
        button.tintColor = .red
        

        如果图像已准备好显示,请删除alwaysTemplate。

        let image = UIImage(named: "X", in: getBundleForCommon(), compatibleWith: nil)
        button.setImage(image, for: .normal)
        

        【讨论】:

          猜你喜欢
          • 2012-04-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-13
          • 2021-02-17
          相关资源
          最近更新 更多