【问题标题】:Programmatically added button not Showing touch feel in ios以编程方式添加的按钮在 ios 中不显示触摸感
【发布时间】:2018-06-27 06:49:44
【问题描述】:

我在 IOS 应用程序的 UIView 中添加了 UIButton。它在目标操作上工作正常,但是当我按下按钮时,它没有在屏幕上显示按下的感觉。 (当用户触摸它时,普通按钮的标题会变暗)。

我使用了以下代码:

class CustomButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViewLayouts()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupViewLayouts()
    }

    func setupViewLayouts() {

        titleLabel?.font = UIFont.boldSystemFont(ofSize: 16.0)

        backgroundColor = .black
        layer.borderWidth = 1.0
        layer.cornerRadius = 3.0
        layer.borderColor = UIColor.clear.cgColor

        setTitleColor(UIColor.black, for: .normal)
    }
}

var btnLogin: CustomButton = {

        let button = CustomButton()
        button.setTitle("Login", for: .normal)
        button.addTarget(self, action: #selector(btnLogin_Tapped), for: .touchUpInside)
        return button
    }()

addSubview(btnSignIn)

【问题讨论】:

    标签: ios swift uiview uiviewcontroller uibutton


    【解决方案1】:

    高亮效果仅在按钮样式为System 时内置。您应该使用其他初始化程序,例如 CustomButton( style : .system )

    【讨论】:

      【解决方案2】:

      使用以下扩展名:

      extension UIButton {
      
          func setBackgroundColor(color: UIColor, for state: UIControlState) {
              let image = UIImage.image(with: color)
              let insets = UIEdgeInsetsMake(0, 0, 0, 0)
              let stretchable = image.resizableImage(withCapInsets: insets, resizingMode: .tile)
              self.setBackgroundImage(stretchable, for: state)
          }
      }
      

      然后代替这个:

      backgroundColor = .black
      

      使用这个:

      setBackgroundColor(color: .black, for: .normal)
      

      直接设置背景颜色会打乱高亮显示。

      【讨论】:

      • 感谢您的回复。您的解决方案看起来不错。但@CZ54 的答案是核心。为你 +1。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      相关资源
      最近更新 更多