自定义UIButton for Iphone

Ama*_*mal 12 iphone uibutton

我的应用程序中有一个视图,它有许多按钮,这些按钮基于服务器返回的项目数.因此,如果服务器返回说10个项目,则应该有10个按钮,并且单击每个按钮应该呼叫另一个人.

出于上述目的,我创建了一个源自UIButton的自定义按钮类.

@implementation HopitalButton

@synthesize index;
@synthesize button_type;

- (id)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {
        UIImage* img = [UIImage imageNamed:@"dr_btn.png"];
        [img stretchableImageWithLeftCapWidth:10 topCapHeight:10];
        [self setBackgroundImage:img forState:UIControlStateNormal];
        [self setTitleColor:[UIColor colorWithRed:0.698 green:0.118 blue:0.376 alpha:1] forState:UIControlStateNormal] ;
        [self setFont:[UIFont fontWithName:@"Helvetica Bold" size:13]];
        self.titleLabel.textColor = [UIColor colorWithRed:178 green:48 blue:95 alpha:1];
        self.adjustsImageWhenHighlighted = YES;
    }
    return self;
}

- (void)dealloc {
    [super dealloc];
}


@end
Run Code Online (Sandbox Code Playgroud)

现在上面代码的问题在于它不会创建与"接口"构建器中默认创建的按钮类似的按钮.边界不见了.

我通过以下代码创建上述类型的按钮:

    HopitalButton* hb = [[HopitalButton alloc] init];
    hb.button_type = @"call";
    hb.frame = CGRectMake(50, 50 + i * 67, 220, 40);
    [self.scroll_view addSubview:hb];
    [hb setTitle:[[[self.office_full_list objectAtIndex:i] objectForKey:@"Staff" ]objectForKey:@"FullName"] forState:UIControlStateNormal];
    hb.index = [NSNumber numberWithInt:[self.button_items count]];
    [self.button_items insertObject:hb atIndex:[self.button_items count]];
    [hb addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

我没有找到设置此自定义按钮的按钮类型的方法.我有办法做到吗?或者有更好的方法来设计代码.

con*_*are 27

首先从带有边框的可伸缩图像开始:

alt text http://grab.by/4lP

然后,您创建一个拉伸图像作为背景的按钮并应用文本.

INDEX_OFFSET = 82753; // random

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(kLeftMargin, 10, self.view.bounds.size.width - kLeftMargin - kRightMargin, 52)];
[sampleButton setTitle:@"Button Title" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];
[sampleButton setTag:<INDEX>+INDEX_OFFSET];
[sampleButton setBackgroundImage:[[UIImage imageNamed:@"redButton.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
[sampleButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton];
Run Code Online (Sandbox Code Playgroud)

显然,您需要调整框架原点和大小以匹配您的应用程序,以及目标,选择器和标题.和


Pet*_*chl 6

[sampleButton setFont:[UIFont boldSystemFontOfSize:20]]; 
Run Code Online (Sandbox Code Playgroud)

现在不推荐使用setFont,而是使用titleLabel.font属性

sampleButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
Run Code Online (Sandbox Code Playgroud)