UIButton 在动态创建时不突出显示



我在表的cellForRowAtIndexPath:方法中有一个动态创建的UIButton。它可以正常加载,并且可以选择,但在选择时不会执行突出显示动画。我尝试添加:

if(commandButton.isHighlighted),并且在选择时不会触发。以下是我加载单元格的方式:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* CellIdentifier=@"CommandCell";
    UITableViewCell* commandCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    UIButton* commandButton = [[UIButton alloc]initWithFrame:commandCell.frame];
    [commandButton setTitle:@"Title" forState:UIControlStateNormal];
    [commandCell.contentView addSubview:commandButton];
    commandButton.backgroundColor = [UIColor blackColor];
    return commandCell;
}

每当我点击它时,commandButton都不会突出显示......

编辑:这是一个愚蠢的问题,我没有按住鼠标足够长的时间。对于那些有类似问题的人,只需在iOS模拟器中按住按钮更长时间即可。

这可以帮助您将波纹管代码添加到代码中

如果你想在tuchupinside上看到一些图像,那么下面的代码。

[commandButton setBackgroundImage:/*add you image using UIImage*/forState: UIControlStateHighlighted];

如果你想要简单(当它出现在Tuchupinside的按钮中时的默认背景颜色)。

UIButton *buttonTap=[UIButton buttonWithType:UIButtonTypeRoundedRect];

并像这样设置框架

buttonTap.frame=commandCell.frame;
//make some adjustment as per requied.

如果你想要一些模糊类型效果(半部分选择)然后你去

UIButtonTypeCustom //type

下一行中创建的UIButton

UIButton* commandButton = [[UIButton alloc]initWithFrame:commandCell.frame];

默认情况下是自定义样式的UIButton。对于此按钮,您必须手动设置所有属性。你想要的是这个:

UIButton *commandButton = [UIButton buttonWithType:UIButtonTypeSystem];
[commandButton setFrame:cell.frame];

UIButtonTypeSystem包含您要查找的样式。

希望这有帮助!

我不知道在哪里

使用它? 但我的建议仍然是,如果您要将按钮添加到单元格中,请为按钮添加标签,例如:

UIButton* commandButton = [[UIButton alloc]initWithFrame:commandCell.frame];
[commandButton setTitle:@"Title" forState:UIControlStateNormal];
commandButton.tag = 1;
[commandCell addSubview:commandButton];
commandButton.backgroundColor = [UIColor blackColor];

并在访问同一按钮时;

您必须获取单击按钮的单元格

   UIButton *button =(UIButton *)[cell viewWithTag:1];

在此按钮上,您可以使用:

if(commandButton.isHighlighted)

在将按钮添加到单元格视图之前,请尝试添加:

NSArray * views = [commandCell.contentView subviews];
for (UIView *object in views) {
    [object removeFromSuperview ];
}

因为也许您有多个单元格一个接一个,所以实际上单击的按钮是"最底层单元格视图"按钮。

最新更新