【问题标题】:Any other option for Making a UIButton look disable?使 UIButton 看起来禁用的任何其他选项?
【发布时间】:2012-02-08 18:33:58
【问题描述】:

我正在尝试使用以下代码使 UIButton 看起来已禁用:

btnYourButton.alpha = 0.6f;
btnYourButton.enabled = NO;

启用时(当然看起来启用)

btnYourButton.alpha = 1.0f;
btnYourButton.enabled = YES;

有没有什么方法可以让我在一个语句中同时执行这两项操作(使 UIButton 禁用/启用并使其看起来禁用/启用)?

【问题讨论】:

    标签: ios user-interface uibutton user-interaction


    【解决方案1】:

    或者您可以尝试子类化 UIButton,例如:

    文件 MyKindOfButton.h

    #import <UIKit/UIKit.h>
    
    @interface MyKindOfButton : UIButton
    
    @end
    

    文件 MyKindOfButton.m

    #import "MyKindOfButton.h"
    
    @implementation MyKindOfButton
    
    - (void)setEnabled:(BOOL)enabled {
    
        [super setEnabled: enabled];
    
        if (enabled) {
            self.alpha = 1.0f;
        } else {
            self.alpha = 0.6f;
    
        }
    }
    
    @end
    

    【讨论】:

      【解决方案2】:

      我知道这是一个非常古老的问题,但这是一个非常好的解决方案。只需创建一个 UIColor 类别并添加此方法即可。

      + (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
      {
          UIGraphicsBeginImageContext(size);
          CGContextRef context = UIGraphicsGetCurrentContext();
      
          CGContextSetFillColorWithColor(context, color.CGColor);
          CGContextFillRect(context, (CGRect){.size = size});
      
          UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();
      
          return image;
      }
      
      + (UIImage *)imageWithColor:(UIColor *)color
      {
          return [UIImage imageWithColor:color size:CGSizeMake(1, 1)];
      }
      

      现在您可以将 backgroundImage 设置为您想要的任何颜色,它会自动为您处理禁用外观。

      [button setTitleColor:[UIColor someColor] forState:UIControlStateNormal];
      

      【讨论】:

        【解决方案3】:

        另一个选项是更改禁用状态的文本颜色(例如变为浅灰色)。在故事板编辑器中,从 State Config 弹出按钮中选择 Disabled,然后使用 Text Color 弹出按钮更改文本颜色。在代码中,使用 -setTitleColor:forState: 消息。

        (我意识到这是一篇较旧的帖子,但我认为其他人可能会喜欢这个选项)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-29
          • 1970-01-01
          • 2011-11-30
          • 1970-01-01
          • 1970-01-01
          • 2011-12-16
          • 1970-01-01
          • 2014-07-12
          相关资源
          最近更新 更多