iPhone应用程序创建包含UITextField和UIButton的自定义UIView

时间:2010-05-31 13:30:16

标签: iphone

我是iPhone编程新手。我有一个问题。我需要创建一个自定义用户控件,我将添加到我的UIScrollView dinamically。该控件有一个UITextField和一个UIButton。请参阅以下代码:

#import <UIKit/UIKit.h>
@interface FieldWithValueControl : UIView {
    UITextField *txtTagName;
    UIButton *addButton;
}
@property (nonatomic, readonly) UITextField *txtTagName;
@property (nonatomic, readonly) UIButton *addButton;
@end

#import "FieldWithValueControl.h"
#define ITEM_SPACING 10
#define ITEM_HEIGHT 20
#define SWITCHBOX_WIDTH 100
#define SCREEN_WIDTH 320
#define ITEM_FONT_SIZE 14
#define TEXTBOX_WIDTH 150
@implementation FieldWithValueControl

@synthesize txtTagName;
@synthesize addButton;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
        txtTagName = [[UITextField  alloc] initWithFrame:CGRectMake(0, 0, TEXTBOX_WIDTH, ITEM_HEIGHT)];
        txtTagName.borderStyle = UITextBorderStyleRoundedRect;

        addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
        [addButton setFrame:CGRectMake(ITEM_SPACING + TEXTBOX_WIDTH, 0, ITEM_HEIGHT, ITEM_HEIGHT)];
        [addButton addTarget:self action:@selector(addButtonTouched:)
            forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:txtTagName];
        [self addSubview:addButton];
    }
    return self;
}
- (void)addButtonTouched:sender
{
    UIButton *button = (UIButton*)sender;
    NSString *title = [button titleLabel].text;
}
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
- (void)dealloc {
    [txtTagName release];
    [addButton release];
        [super dealloc];
}
@end

在我的代码中,我创建了该类的一个对象,并将其添加到表单上的scrollView。

FieldWithValueControl *newTagControl = (FieldWithValueControl*)[[FieldWithValueControl alloc] initWithFrame:CGRectMake(ITEM_SPACING, currentOffset + ITEM_SPACING, 0, 0)];
[scrollView addSubview:newTagControl];

控件看起来很好,但如果我点击文本框或按钮没有任何反应。键盘没有出现,按钮不可点击等。

2 个答案:

答案 0 :(得分:0)

为控件设置widthheight值超过0:

 FieldWithValueControl *newTagControl = [[FieldWithValueControl alloc] initWithFrame:
    CGRectMake(ITEM_SPACING, currentOffset + ITEM_SPACING, 100, 200)];

答案 1 :(得分:-1)

尝试将delegate设置为self