按下时 UIButton 不突出显示 [英] UIButton is not highlighting when pressed

查看:29
本文介绍了按下时 UIButton 不突出显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 UIButton 实例在按下时未突出显示.我很确定我的代码是正确的.这只发生在我正在使用的这个特定类中.我猜是因为该函数已被我遵守的协议覆盖.

我想让 UIButton 突出显示默认方式,但我必须手动完成.如何在按下时强制突出显示按钮,它的默认设置是什么(在颜色方面),以便与所有其他按钮保持一致?

这是我当前的代码:

 让 backButton = UIButton()backButton.setTitle("返回", for: .normal)backButton.setTitleColor(UIColor.black, for: .normal)backButton.adjustsImageWhenHighlighted = trueRevealBar.addSubview(backButton)backButton.snp.makeConstraints { (make) ->无效make.center.equalTo(RevealBar)make.width.equalTo(RevealBar)make.height.equalTo(RevealBar)}backButton.addTarget(self, action: #selector(self.goBack), for: .touchUpInside)

解决方案

使用 UIButton(type buttonType: .system) 而不是 UIButton() 来初始化按钮.

当您使用后者时,它不会正确设置按钮突出显示,因为默认按钮类型是 UIButtonType.custom,它旨在作为没有任何默认样式或突出显示行为的空白板.

注意,来自 Apple 的 UIButton 文档:p><块引用>

按钮的类型定义了它的基本外观和行为.您指定使用 init(type:) 方法在创建时按钮的类型或在您的故事板文件中.创建按钮后,无法更改它的类型. 最常用的按钮类型是自定义和系统类型,但在适当的时候使用其他类型.

My UIButton instance is not highlighting when pressed. I'm pretty sure my code is correct. This only happens in this specific class that I am using. I'm guessing because the function has been overridden by a protocol that I am conforming to.

I want to make the UIButton highlight the default way, but I have to do it manually. How can I force highlight the button when pressed, and what are the default settings for it (in terms of colour), so that it is consistent with all the other buttons?

Here is my current code:

    let backButton = UIButton()
    backButton.setTitle("back", for: .normal)
    backButton.setTitleColor(UIColor.black, for: .normal)
    backButton.adjustsImageWhenHighlighted = true
    RevealBar.addSubview(backButton)
    backButton.snp.makeConstraints { (make) -> Void in
        make.center.equalTo(RevealBar)
        make.width.equalTo(RevealBar)
        make.height.equalTo(RevealBar)
    }

    backButton.addTarget(self, action: #selector(self.goBack), for: .touchUpInside)

解决方案

Initialize the button using UIButton(type buttonType: .system) instead of UIButton().

When you use the latter it won't properly set up button highlighting because the default button type is UIButtonType.custom, which is intended as a blank slate without any of the default styling or highlighting behaviour.

Note, from Apple's UIButton documentation:

A button’s type defines its basic appearance and behavior. You specify the type of a button at creation time using the init(type:) method or in your storyboard file. After creating a button, you cannot change its type. The most commonly used button types are the Custom and System types, but use the other types when appropriate.

这篇关于按下时 UIButton 不突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆