【问题标题】:How to make a button to behave like a table view cell如何使按钮表现得像表格视图单元格
【发布时间】:2014-08-17 03:11:21
【问题描述】:

如何自定义 UIButton 使其表现得像表格视图单元格? 我试过在 Interface Builder 中制作它,但由于按钮是不可见的并且没有图像,所以当你按下它时它永远不会被突出显示。我想要这种变灰的行为,就像在表格视图单元格上一样。 有人知道怎么做吗?

【问题讨论】:

  • 我不明白。如果您的按钮是不可见的,那么您当然不会看到它,因此它不会有任何突出显示。
  • 为什么是按钮?你也可以在 UIView 上实现这一点,只需要在 View 上使用 TapGesture,点击更改背景颜色,一段时间后使用 performselector 更改为正常。
  • 好的,你当然可以制作自己的按钮,但我想也许有一种简单的方法可以使用 UIButton 并做同样的事情......无论如何谢谢

标签: ios objective-c xcode uibutton interface-builder


【解决方案1】:

我创建了一个Custom Control,其行为类似于UITableViewCell。见下面的代码

MyButton.h

#import <UIKit/UIKit.h>

@interface MyButton : UIView
- (id)initWithFrame:(CGRect)frame selector:(SEL)sel target:(id)target;
@end

MyButton.m

#import "MyButton.h"
#import <QuartzCore/QuartzCore.h>


@interface MyButton()
@property(assign)SEL selector;
@property(assign)id target;
@end

@implementation MyButton

- (id)initWithFrame:(CGRect)frame selector:(SEL)sel target:(id)target
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        self.selector=sel;
        self.target=target;

        self.backgroundColor=[UIColor darkGrayColor];
        self.layer.cornerRadius=5.0;
        UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [self addGestureRecognizer:tapGesture];
    }
    return self;
}

-(void)tapAction:(id)sender{

    [UIView animateWithDuration:.2 animations:^{
        [self setBackgroundColor:[UIColor lightGrayColor]];
    }];

    [self performSelector:@selector(deSelect) withObject:nil afterDelay:.2];
}

-(void)deSelect{

    [UIView animateWithDuration:.2 animations:^{
        [self setBackgroundColor:[UIColor darkGrayColor]];
    } completion:^(BOOL finished) {
        [_target performSelector:_selector withObject:self];
    }];

}

/*- (void)drawRect:(CGRect)rect
{
}*/

@end

由于它使用UIView,您可以在此控件上轻松添加或绘制任何内容,并轻松自定义。

希望这会有所帮助。 干杯。

【讨论】:

    【解决方案2】:

    简单的方法:

    制作一个 10x10px 的灰色方形 png 图片,保存并命名为“greayButtBkg.png”,然后将其拖到 XCode 中的 SupportingFiles 中。 在 .h 文件中声明按钮的 Outlet,在 .m 文件中声明 IBAction 方法。

    yourFile.h:

    @property (weak, nonatomic) IBOutlet UIButton *myButton;
    

    yourFile.m:

    - (IBAction)pressButton:(id)sender {
        [_myButton setBackgroundImage:[UIImage imageNamed:@"greyButtBkg"] forState:UIControlStateHighlighted];
    }
    

    当您点击按钮时,您的 Button 将获得灰色背景色,当您松开手指时返回其默认的 clearColor。

    希望这会有所帮助!

    【讨论】:

    • 是的!它完美地工作。多亏了你,我发现了如何在 Interface Builder 中修复它。在“属性检查器”中,将“状态配置”更改为“突出显示”并在“背景”下键入您创建的灰色图像的名称。那么你就不需要声明一个 Outlet。
    猜你喜欢
    • 1970-01-01
    • 2014-10-25
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多