ios - UIButton:设置 ImageView 的背景(不设置图像)

标签 ios uibutton uikit

如何在不设置图像的情况下更改 UIButton 上 ImageView 的背景颜色? (例如,我在按钮文本旁边有一个红色方 block )。

当我简单地设置 mybutton.imageView.backgroundColor = UIColor.red 并将 ImageView 的约束设置为 28x28px 时。我没有看到红色方 block 。

谢谢。

澄清一下:我只想为 UIButton 的 ImageView 设置背景颜色 - 我不想为整个按钮着色!

最佳答案

您将问题标记为 SwiftObjective-C,所以...

在 Swift 中,您可以使用此扩展创建具有特定颜色的“空白”图像:

public extension UIImage {
    public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        guard let cgImage = image?.cgImage else { return nil }
        self.init(cgImage: cgImage)
    }
}

然后,添加“按钮文本旁边的红色方 block ”:

    let btnImage = UIImage(color: .red, size: CGSize(width: 28, height: 28))
    btn.setImage(btnImage, for: .normal)

如果您需要在 Obj-C 中执行此操作,则过程相同:

- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)sz {
    CGRect rect = CGRectMake(0.0f, 0.0f, sz.width, sz.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

    UIImage *btnImage = [self imageWithColor:[UIColor redColor] andSize:CGSizeMake(28.0, 28.0)];
    [_btn setImage:btnImage forState:UIControlStateNormal];

注意:确保您的 UIButton 类型设置为 Custom,否则图像将被“着色”。

关于ios - UIButton:设置 ImageView 的背景(不设置图像),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47153925/

相关文章:

iphone - 每秒多次更改 UIButton 背景图像

ios - 在 iOS 上发布时获得接触

iphone - 如何更改 UISearchBar 以用文本替换文本字段内的搜索图标

ios - 使 View 变暗,就像禁用一样

swift - 如何让UIViewController从下往上滑动而不褪色之前的 View ?

ios - UIButton:使点击区域大于默认点击区域

ios - UITableView 单元格约束问题 - Swift

ios - 如何在 UITextView 中绘制文本

ios - 在堆栈 View 中调整按钮的大小

ios - UIImageView 的 tintColor 不适用于 Storyboard,但适用于代码