触摸时UIButton没有显示高亮显示

Hur*_*rkS 10 objective-c uibutton ios

我试图突出我的UIButton与自定义UIColor浅灰色,并使文本变白...但我不知道如何做到这...这是我创建UIButton到目前为止任何帮助将不胜感激.

cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    cancelButton.frame = CGRectMake(10.0, calculatorView.frame.size.height-55, 100.0, 45.0);
    [cancelButton addTarget:self action:@selector(calculateMethod:)forControlEvents:UIControlEventTouchDown];
    [[cancelButton titleLabel] setFont:[UIFont fontWithName: @"Super-text" size:20.0]];
    [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

Chr*_*men 18

要获得突出显示的白色文本,请执

[cancelButton setTitleColor:[UIColor whiteColor]
                       forState:UIControlStateHighlighted];
Run Code Online (Sandbox Code Playgroud)

要获得更改背景,您需要执行setBackgroundImage:forState:并使用带图案颜色的UIImage或子类UIButton,并在setHighlight:方法中设置适当的背景颜色.

编辑:Swift 2.x版本

cancelButton.setTitleColor(.whiteColor(), forState: Highlighted)
Run Code Online (Sandbox Code Playgroud)

编辑:Swift 3.0版本

cancelButton.setTitleColor(.white, for: .highlighted)
Run Code Online (Sandbox Code Playgroud)


nit*_*iya 6

您可以创建图像以使用颜色填充背景.

[cancelButton setBackgroundImage:[self setBackgroundImageByColor:[UIColor blueColor] withFrame:cancelButton.frame cornerRadius:0] forState:UIControlStateHighlighted];
[cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
Run Code Online (Sandbox Code Playgroud)

此方法构建的图像的按钮与所述颜色的固体背景大小的backgroundColor.

-(UIImage *)setBackgroundImageByColor:(UIColor *)backgroundColor withFrame:(CGRect )rect cornerRadius:(float)radius{

    UIView *tcv = [[UIView alloc] initWithFrame:rect];
    [tcv setBackgroundColor:backgroundColor];

    CGSize gcSize = tcv.frame.size;
    UIGraphicsBeginImageContext(gcSize);
    [tcv.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    const CGRect RECT = CGRectMake(0, 0, image.size.width, image.size.height);;
    [[UIBezierPath bezierPathWithRoundedRect:RECT cornerRadius:radius] addClip];
    [image drawInRect:RECT];
    UIImage* imageNew = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageNew;
}
Run Code Online (Sandbox Code Playgroud)