0

我正在开发一个 iPhone 应用程序并尝试创建一个带有标题的自定义 TextField,如下图所示。在此处输入图像描述

正如您从图像中看到的,标签由用户输入或从数据库中读取的值更改。除了名称之外,还有其他文本字段。

我不确定我应该如何实现这个自定义文本字段?

我认为将带有“名称:”文本的图像放置到文本字段的背景并在其上放置“标签”值的一种方法是放置只有边框的图像并在其上插入“名称:标签”文本。

这些方法是否合适,或者是否有其他最佳方法可用?

编辑:图像上的边框是文本字段的边框;“名称:标签”也在文本字段上方。

4

1 回答 1

0

Simply put another label with the desired text behind or beside the label or text field that is going to be filled. You can set the font and textColor and even the alpha according to your taste.

Make sure that if they overlap (which they should not!) the backgroundColor property of the label is set to [UIColor clearColor].

You could subclass UITextField like this:

@interface LabeledTextField : UIView
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UITextField *textField;
@end


#define kPercentWidth 0.5
@implementation LabeledTextField
-initWithCoder:(NSCoder)aDecoder {
   self = [super initWithCoder:aDecoder];
   if (self) {
      CGRect f = self.frame;
      _label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,
               f.size.width*kPercentWidth,f.size.height)];
      _textField = [[UITextField alloc] initWithFrame:CGRectMake(0,0,
               f.size.width*(1-kPercentWidth),f.size.height)];
      [self addSubView:_label]; 
      [self addSubView:_textField];
   }
   return self;
}
@end

You could then use it like this: insert a UIView into your storyboard view controller and change the class to your LabeledTextField. This would ensure initWithCoder is called. Otherwise, you might have to put the init code into its own setup function and call it from your override of initWithFrame. Make sure you wire up the view with your outlet

// .h
#include LabeledTextField.h
//...
@property (nonatomic, strong) IBOutlet LabeledTextField *labeledTextField;

// .m, in some method
labeledTextField.textField.text = @"editable text";
labeledTextField.label.text = @"non-editable text";

Similarly, you could modify all properties of the label and text field, including colors, fonts etc.

于 2012-08-27T20:49:22.013 回答