我需要通过代码生成一个自定义按钮,这就是我目前正在做的。
-(void) initialiseButtons
{
int ypos = playerImage.frame.origin.y + playerImage.frame.size.height + 8;
for(int i=0; i<totalButtons; i++)
{
UIButton *newButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[newButton setFrame:CGRectMake(20, ypos, 220, 30)];
newButton.tag = 10 + i;
[newButton addTarget:self action:@selector(statTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.frontView addSubview:newButton];
ypos += 30 + 7;
}
}
这通过代码完美地创建了空白按钮,给它们一个标签并在 touchUpInside 上分配一个回调函数。
自定义按钮需要能够在按下时显示图像。 它需要能够绘制 2 段文本。 1 个与按钮的左侧对齐,1 个与按钮的右侧对齐。
我的老板建议我使用 View 而不是按钮。我不明白这将如何工作。当我开始考虑它时,我认为它需要一个专用于按钮的 View Controller 。还有一些绘制方法?这听起来很复杂,我不明白如何做到这一点。
有没有一种更简单的方法,可以让自定义类覆盖 UIButton?我之前制作了一个简单的测试类,但是当我使用按钮位置代替普通 UIButton 类时,没有在按钮位置绘制任何内容。我希望我会看到绘制的 buttonUp.png。
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CardButton : UIButton {
}
@end
#import "CardButton.h"
#import <UIKit/UIKit.h>
@implementation CardButton
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self setImage:[UIImage imageNamed:@"buttonUp.png"] forStates:UIControlStateNormal];
self.adjustsImageWhenHighlighted = YES;
}
return self;
}
@end
有人能给我一些建议吗?我现在很受阻。一直在阅读与按钮相关的其他各种主题,但没有任何内容让我清楚地知道如何解决这个问题
最佳答案
就个人而言,我会继承 UIButton。尽管一直在谈论您不能对 UIButton 进行子类化,Apple 甚至在 UIButton 文档中讨论了对 UIButton 进行子类化。
在子类中,我将创建一个带有两个标签(或图像或其他)的 UIView,并将它们作为 subview 添加到按钮(确保将文本的交互设置为 FALSE)。
这很棒的地方在于它利用了 UIButton 代码并让您免于重新发明轮子。
关于iphone - 使用 UIView 或覆盖 UIButton 制作自定义按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3679239/