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

问题描述:

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

#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 

在我的代码创建一个类的对象,并将其添加到滚动视图的形式。

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

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

尝试将delegate设置为self

更多的则0

设置widthheight值的控制:

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