UIButton的imageView属性和隐藏/ alpha值

Mic*_*chs 3 hidden alpha uibutton uikit ios

我有一个UIButton应该在某些情况下显示活动指示器而不是图像.我现在所做的是将按钮的imageView的隐藏属性设置为YES并返回.我也尝试将alpha值设置为0.0f并返回1.0f.

这一直有效,直到按钮的状态发生变化.这会重置imageView的属性并导致隐藏== NO和alpha == 1.0f.

有没有人做过类似的事情,或者知道如何隐藏按钮的imageView,而其余部分仍然可见?

Iro*_*Man 16

你可以通过使用视图层的transform属性来实现这一点

隐藏

SWIFT代码

button.imageView?.layer.transform = CATransform3DMakeScale(0.0, 0.0, 0.0)
Run Code Online (Sandbox Code Playgroud)

objective-C代码

button.imageView.layer.transform = CATransform3DMakeScale(0, 0, 0);
Run Code Online (Sandbox Code Playgroud)

取消隐藏

button.imageView?.layer.transform = CATransform3DIdentity
Run Code Online (Sandbox Code Playgroud)

objective-C代码

button.imageView.layer.transform = CATransform3DIdentity
Run Code Online (Sandbox Code Playgroud)


Den*_*nis 5

很简单。按钮有不同的状态。只需为选定状态设置零图像,将您的图像设置为正常状态。当您想要将活动指示器设置按钮状态显示为选中状态并将指示器添加为按钮子视图时。

- (void)initializeButton {
    button = [[UIButton alloc] init];
    [button addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];

    [button setImage:[[UIImage alloc] init] forState:UIControlStateSelected]; //zero image
    [button setImage:yourImage forState:UIControlStateSelected]; //your image
}

- (void)buttonDidClick:(UIButton *)button {
    button.selected = YES;
    /* Add yor activity indicator with some view tag or save reference to it */
}
Run Code Online (Sandbox Code Playgroud)

活动完成后调用 next 方法

- (void)finishActivityWithButton:(UIButton *)button {
    button.selected = NO;
    /* Remove your activity indicator from button */
}
Run Code Online (Sandbox Code Playgroud)