【问题标题】:Highlighting my buttons in iOS 7在 iOS 7 中突出显示我的按钮
【发布时间】:2013-12-11 07:19:53
【问题描述】:

我正在 iOS 7 中制作自定义键盘,我希望按钮的背景颜色在用户点击时改变。但是,我无法获得这样做的按钮。在我分配给按钮的 IBAction 中,我使用的代码是

    if(button.highlighted==YES){
    button.backgroundColor = [UIColor blackColor]; //Change background color
    button.titleLabel.textColor = [UIColor whiteColor]; //Change text color
    }

我在这里做错了什么?我是否滥用“突出显示”?当我运行这段代码时,它似乎根本不会影响用户界面,我不确定用什么替换它。

【问题讨论】:

    标签: iphone objective-c ios7 uibutton


    【解决方案1】:

    改变按钮的高亮状态:

    [YourButton setBackgroundImage:[self imageWithColor:[UIColor greenColor]] forState:UIControlStateHighlighted];
    

    并将此方法添加到您的视图控制器:

    - (UIImage *)imageWithColor:(UIColor *)color {
       CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
       UIGraphicsBeginImageContext(rect.size);
       CGContextRef context = UIGraphicsGetCurrentContext();
    
       CGContextSetFillColorWithColor(context, [color CGColor]);
       CGContextFillRect(context, rect);
    
       UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();
    
       return image;
    }
    

    【讨论】:

    • 我推荐缓存这种方式生成的图片
    【解决方案2】:

    你也可以在xib 中做简单的事情。按照下面的屏幕截图:-

    1) 选择button,然后在drawingcontrol 部分启用show Touch on HighlightHighlighted

    【讨论】:

    • 为此您需要自定义按钮
    • 这意味着 type 必须从 system 更改为 custom ??
    • 除非您希望按钮最初显示为突出显示,否则不要选中突出显示
    【解决方案3】:
    + (UIImage *)imageWithColor:(UIColor *)color
    {
        CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        CGContextSetFillColorWithColor(context, [color CGColor]);
        CGContextFillRect(context, rect);
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    }
    

    您使用此方法创建一个图像,并使用setBackgroundImage:forState: 方法设置您的按钮

    【讨论】:

      【解决方案4】:

      在 Swift 中,您可以这样做:

      extension UIButton {
      func setBackgroundColor(color: UIColor, forState: UIControlState) {
          UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
          CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
          CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
          let colorImage = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()
      
          self.setBackgroundImage(colorImage, forState: forState)
      }}
      

      只要把它写在任何课程之外,你就可以像这样在任何地方使用它:

      yourButton.setBackgroundColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
      

      Source

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-27
        • 2013-03-26
        • 2012-02-11
        • 2012-08-11
        • 1970-01-01
        • 2019-04-27
        • 1970-01-01
        相关资源
        最近更新 更多