最新消息:20210917 已从crifan.com换到crifan.org

[整理]swift UIButton是否选中时标题文字颜色

Swift crifan 2635浏览 0评论

之前设置Button的标题颜色时用的是:

        self.sendMessageButton.tintColor = UIColor.whiteColor()
        self.sendMessageButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)

后来才知道:

此处的

sendMessageButton.tintColor

是没用的,因为根据tintColor的解释是:

var tintColor: UIColor! { get set }
Description
The tint color to apply to the button title and image.
In iOS v7.0, all subclasses of UIView derive their behavior for tintColor from the base class. See the discussion of tintColor at the UIView level for more information.
This property has no default effect for buttons with type UIButtonTypeCustom. For custom buttons, you must implement any behavior related to tintColor yourself.

即:

对于此处的button:

sendMessageButton = UIButton()

是属于自定义的button

(否则应该是系统的button:

sendMessageButton = UIButton(type: UIButtonType.xxx)

所以此处的tintColor是无效的

-》所以只能通过:

sendMessageButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)

去设置正常情况下的button的颜色。

Swift之贪婪的UIButton – 一叶博客

中解释的,直接设置select属性即可更新图片

-》抽空更新项目中的内容:

然后此处,另外一个地方,也用到了:

设置按钮不同状态下的,标题文字的内容,标题文字的颜色等等的变化:

        let acceptButton:UIButton = UIButton()
        acceptButton.backgroundColor = ColorAppBackground
        acceptButton.setTitle("接受", forState: UIControlState.Normal)
        acceptButton.setTitle("已接受", forState: UIControlState.Selected)
        acceptButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        acceptButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Selected)
        acceptButton.addTarget(self, action: Selector("acceptInvitation:"), forControlEvents: UIControlEvents.TouchUpInside)
        acceptButton.backgroundColor = ColorButtonBackgroudDarkBlue
        acceptButton.titleLabel?.font = UIFont.systemFontOfSize(13)
        acceptButton.layer.cornerRadius = 4
        cell.accessoryView?.addSubview(acceptButton)
    func acceptInvitation(button:UIButton){
        acceptButton.selected = true
        acceptButton.backgroundColor = UIColor.clearColor()
        acceptButton.layer.cornerRadius = 0
    }

而达到:

点击后,文字和文字的颜色(已经手动设置的button的背景色)都发生变化了。

效果如下:

点击后:

-》

如此,就不用再去麻烦的,在点击按钮之后,再去把button移除,另外添加新的label了。

转载请注明:在路上 » [整理]swift UIButton是否选中时标题文字颜色

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
94 queries in 0.207 seconds, using 23.35MB memory