如何在iOS中创建一个非常自定义的uibutton,如UITableViewCellStyleSubtitle

Atm*_*tma 2 uibutton ios

我想创建一个按钮,其图像,标题和描述类似于UITableViewCellStyleSubtitle.我想以编程方式执行此操作.

有谁知道我怎么能做到这一点?

小智 6

您可以创建UIButton类的类别.这是为您准备的准系统:

在.h文件中:

@interface UIButton (YourCategoryName)
    - (void)setupButton:(NSString *)title image:(UIImage *)image description:(NSString *) description;
@end
Run Code Online (Sandbox Code Playgroud)

在.m文件中:

@implementation UIButton(YourCategoryName)

- void)setupButton:(NSString *)title image:(UIImage *)image description:(NSString *) description {
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 200, 50)]];
    [self addSubview:titleLabel];
    [titleLabel release];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:image];
    [self addSubview:imageView]; 
    [imageView release];

    UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 60, 200, 100)];
    [self addSubview:descriptionLabel];
    [descriptionLabel release];
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,您可以根据需要调整帧.设置完毕后,只需在view/viewcontroller中创建正常的按钮,然后调用上面的方法:

  UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
  myButton.frame = CGRectMake(0, 0, 300, 200);
  [myButton setupButton:myTitle image:myImage description:myDesc];
Run Code Online (Sandbox Code Playgroud)