简体   繁体   English

Swift - 将背景颜色更改为透明

[英]Swift - Changing background color to transparent

I noticed one of my buttons has a value for the background color = 'default'我注意到我的一个按钮的背景颜色值 = 'default'

When the button is highlighted I want to change a different button to also have a 'default' background color, here is my code so far:当按钮突出显示时,我想将不同的按钮更改为也具有“默认”背景颜色,这是我的代码:

@IBAction func buttonTouchUpInside(_ sender: UIButton) {

    registerBtn.setTitleColor(UIColor.white, for: UIControlState.highlighted);
}

How do I achieve this so registerBtn has a background color which is basically transparent?我该如何实现这一点,所以 registerBtn 的背景颜色基本上是透明的?

In the comments I found that:在评论中我发现:

  • Both buttons are created in InterfaceBuilder (IB).这两个按钮都是在 InterfaceBuilder (IB) 中创建的。
  • The background color of each button is either set to default or something else in IB.每个按钮的背景颜色要么设置为默认值,要么设置为 IB 中的其他颜色。
  • The idea is to have the second button have a transparent background color and a white title when the first is highlighted.这个想法是让第二个按钮在第一个按钮突出显示时具有透明的背景颜色和白色标题。

(I'll edit the above as needed. Among the things I'm not entirely sure about is what should happen after when the first button is no longer highlighted.) (我会根据需要编辑上面的内容。我不完全确定的是,当第一个按钮不再突出显示后会发生什么。)

If the above is the situation, you need to do the following:如果是以上情况,则需要进行以下操作:

  • Have the first button do things when either UIControlEventTouchDown or UIControlEventTouchDragEnter happen.当 UIControlEventTouchDownUIControlEventTouchDragEnter 发生时,让第一个按钮执行操作。
  • Have the first button then change the background color of the second through code.让第一个按钮然后通过代码更改第二个按钮的背景颜色。

Probably the easiest way to do this is not through IB, but instead through code.可能最简单的方法不是通过 IB,而是通过代码。 After adding your buttons in IB, create IBOutlets for both of them.在 IB 中添加按钮后,为它们创建 IBOutlets。 Then you can do this:然后你可以这样做:

@IBOutlet weak var firstButton: UIButton!
@IBOutlet weak var secondButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    firstButton.addTarget(self, action: #selector(highlightSecondButton), for: .touchDown)
    firstButton.addTarget(self, action: #selector(highlightSecondButton), for: .touchDragEnter)
}

func highlightSecondButton(_ sender:UIButton) {
    secondButton.setTitleColor(UIColor.white, for: UIControlState.normal)
    secondButton.backgroundColor = nil
}

Use UIColor.clear to make a color transparent.使用UIColor.clear使颜色透明。

It is very confusing that Apple calls it "default" instead of "clear."苹果称其为“默认”而不是“清晰”,这非常令人困惑。

Swift迅速

button.backgroundColor = UIColor.clear

objective-C客观-C

button.backgroundColor = [UIColor clearColor];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM