iPhone app. Creating a custom UIView that contains UITextField and UIButton.

Posted by Dmitry Burchik on Stack Overflow See other posts from Stack Overflow or by Dmitry Burchik
Published on 2010-05-31T13:30:15Z Indexed on 2010/05/31 13:33 UTC
Read the original article Hit count: 231

Filed under:

Hi all. I am new to iPhone programming. And I have an issue. I need to create a custom user control that I will add to my UIScrollView dinamically. The control has an UITextField and an UIButton. See the code below:

#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

In my code I create an object of that class and add it to scrollView on form.

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

The control looks fine, but if I click to the textbox or to the button nothing happens. Keyboard doesn't appear, the button is not clickable etc.

© Stack Overflow or respective owner

Related posts about iphone