OGeek|极客世界-中国程序员成长平台

标题: ios - 当按钮被选中时,使色调颜色填充框架 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:21
标题: ios - 当按钮被选中时,使色调颜色填充框架

当一个 UIButton 被选中时,我怎样才能让它选择它的全帧?这就是我的意思:

enter image description here

所以橙色是 UIButtons 框架,蓝色是它被选中的时候。我怎样才能让蓝色填满整个框架? (所以你不会看到橙色。)

更新

enter image description here



Best Answer-推荐答案


我假设橙色是 UIButtonsuperview 并且 superview 是您想要的色调应用于。如果是这种情况,那么我会向按钮添加一个目标,以更改 super View 的 backgroundColor 以匹配按钮的 tintColor。像这样的东西应该可以工作:

[myButton addTarget:self
             actionselector(setButtonSuperviewToTintColor
   forControlEvents:UIControlEventTouchUpInside];

然后在 Controller 的其他地方添加:

- (void)setButtonSuperviewToTintColorUIButton *)sender {
    sender.superview.backgroundColor = sender.tintColor;
}

如果 super View 不是您想要调整的,那么创建一个方法将UIButton的背景颜色更改为它的色调。

[myButton addTarget:self
             actionselector(setButtonBackgroundColorToTintColor
   forControlEvents:UIControlEventTouchUpInside];

和其他地方:

- (void)setButtonBackgroundColorToTintColorUIButton *)sender {
    sender.backgroundColor = sender.tintColor;
}

但是,如果您只是希望它成为 selected 颜色,那么已经有一种方法可以做到这一点。不幸的是,它被设计用于处理图像。但是,从图像中制作颜色很容易。所以,这应该适合你:

CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,
                               [[UIColor blueColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[myButton setBackgroundImage:img forState:UIControlStateSelected];

关于ios - 当按钮被选中时,使色调颜色填充框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30465327/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4