xcode 在 Swift 中按下 uibutton 时更改色调图像颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34800246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:26:09  来源:igfitidea点击:

Change tint image color when pressing uibutton in Swift

iosswiftxcodeuiscrollviewuibutton

提问by Ruben

I have a scrollview inside a view. Inside the scrollview I create programmatically 5 buttons. Every button loads a different image with a different tag each one. I added a function that is called when pressing the buttons.

我在视图中有一个滚动视图。在滚动视图中,我以编程方式创建了 5 个按钮。每个按钮加载一个不同的图像,每个图像都有不同的标签。我添加了一个按下按钮时调用的函数。

let avatarsListScrollingView = avatarsListView(CGSizeMake(70.0, 55.0), avatarCount: 5)


func avatarsListView(buttonSize:CGSize, avatarCount:Int) -> UIView {

 **CODE**

    for i in 0...(avatarCount-1)  {
        let button = UIButton(type: .Custom)

        **CODE**

        button.setImage(UIImage(named: avatarsList[i]), forState: .Normal)

        button.tag = i
        button.addTarget(self, action: "avatarListSelected:", forControlEvents: .TouchUpInside)

        avatarButtonView.addSubview(button)
    }
    return avatarButtonView

}

Then when pressing the buttons, I call to "avatarListSelected":

然后按下按钮时,我调用“avatarListSelected”:

func avatarListSelected(sender:UIButton){

    if let image = sender.imageView?.image?.imageWithRenderingMode(.AlwaysTemplate) {
        sender.setImage(image, forState: .Normal)
        sender.tintColor = UIColor.redColor()
    }
    self.addAvatarView.reloadInputViews()
}

This function tints the image button to red, it is working fine, but the problem is that when I press some other button, I want the other one goes to the original color. Right now every button that I press gets in red.

此功能将图像按钮着色为红色,它工作正常,但问题是当我按下其他按钮时,我希望另一个按钮变为原始颜色。现在我按下的每个按钮都会变成红色。

I tried to add the call to "self.addAvatarView.reloadInputViews()" to try to "redraw" again all the buttons, but never gets called.

我尝试将调用添加到“self.addAvatarView.reloadInputViews()”以尝试再次“重绘”所有按钮,但从未被调用。

Do you guys know some way to do this?

你们知道有什么方法可以做到这一点吗?

采纳答案by Felipe Florencio

I don't know if is better approach or answer, but, i maybe could delivery this using this approach:

我不知道是否有更好的方法或答案,但是,我也许可以使用这种方法来交付:

Create a method that will "fill" the color for your choice button and "clear" color to others , but its a method that loop through UIScrollView and look for each UIButton. Something like this :

创建一个方法,该方法将为您的选择按钮“填充”颜色并为其他人“清除”颜色,但它是一个循环遍历 UIScrollView 并查找每个 UIButton 的方法。像这样的事情:

func setBackgroundColorButton(color:UIColor , buttonTag:Int){
   for view in self.scrollView.subviews as [UIView] {
      if let btn = view as? UIButton {
         if btn == buttonTag  {
             btn.tintColor = color
         } else {
             btn.tintColor = UIColor.whiteColor()
         }
      }
   }
}

This is the concept, i didn't tested, but maybe just need adjust to search inside your scroll view or similar.

这是概念,我没有测试过,但也许只需要调整以在滚动视图或类似视图中进行搜索。

But with this will be work nice i believe :D

但是我相信这会很好用:D

回答by Ruben

Thanks to everybody! This is the final code that solved the problem:

感谢大家!这是解决问题的最终代码:

func avatarListSelected(sender:UIButton){
    print(sender.tag)

    if let image = sender.imageView?.image?.imageWithRenderingMode(.AlwaysTemplate) {
        sender.setImage(image, forState: .Normal)
        sender.tintColor = UIColor.redColor()
    }

    for view in self.avatarButtonView.subviews as [UIView] {
        if let btn = view as? UIButton {
            if btn.tag != sender.tag  {
                btn.setImage(UIImage(named: avatarsList[btn.tag]), forState: .Normal)
            }
        }
    }
}

回答by lukasbalaz7

Create a property selectedButton: UIButton?and keep a reference to the selected button there. Don't forget to update it in avatarListSelectedmethod and before you change it, if it isn't nil, change its color to original (and then change it).
If the buttons have different original colors, subclass UIButtonclass and keep the original color there.

创建一个属性selectedButton: UIButton?并在那里保留对所选按钮的引用。不要忘记在avatarListSelected方法中更新它,在更改它之前,如果它不是零,请将其颜色更改为原始(然后更改它)。
如果按钮具有不同的原始颜色,则子UIButton类化并保留原始颜色。

回答by Rashwan L

You could do it like this

你可以这样做

for i in 0...5 {
      let button = UIButton(type: .Custom)
      let x = 50 * i + 10
      let y = 50
      button.frame = CGRectMake(CGFloat(x), CGFloat(y), 40, 40)
      button.setTitle("\(i)", forState: .Normal)
      button.tag = i
      button.backgroundColor = UIColor.greenColor()
      button.tintColor = UIColor.blueColor()
      button.addTarget(self, action: "avatarListSelected:", forControlEvents: .TouchUpInside)

     self.view.addSubview(button)
}

func avatarListSelected(sender : UIButton){
        sender.backgroundColor = UIColor.orangeColor()

        for view in self.view.subviews{
            if(view.isKindOfClass(UIButton)){
                let button = view as! UIButton
                if button.tag != sender.tag{
                    button.backgroundColor = UIColor.greenColor()
                }
            }
        }
    }

The frame etc is just for demonstation purpose only, you should of course use your own value. The tintColorproperty is not valid for all button types. Read the documentationfor more information.

框架等仅用于演示目的,您当然应该使用自己的价值。该tintColor属性并非对所有按钮类型都有效。阅读文档以获取更多信息。