目标C:如何创建多行UITextField? [英] Objective C: How to create a multi-line UITextField?

查看:108
本文介绍了目标C:如何创建多行UITextField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:



如何创建多行UITextfield?



http://brettschumann.com/blog/2010/01/15/iphone-multiline-textbox-for-sms-stylechat



并且明确地尝试 Three20 ,这是一个在Facebook等许多应用程序中使用的很棒的库。






编辑:添加BrettSch的摘录umann blog

  #import< uikit uikit.h => 
@interface MultilineTextboxViewController:UIViewController {
IBOutlet UIView * viewTable;
IBOutlet UIView * viewForm;
IBOutlet UITextView * chatBox;
IBOutlet UIButton * chatButton;
}

@property(非原子,保留)UIView * viewTable;
@property(非原子,保留)UIView * viewForm;
@property(非原子,保留)UITextView * chatBox;
@property(非原子,保留)UIButton * chatButton;

- (IBAction)chatButtonClick:(id)sender;
@end
< / uikit>

完成后,当我们设置所有内容时,让我们将我们的项目添加到我们的主要(。 m)文件同时不要忘记取消分配它们。

  @synthesize viewTable; 
@synthesize viewForm;
@synthesize chatBox;
@synthesize chatButton;

- (void)dealloc {
[viewTable release];
[viewForm release];
[chatBox发布];
[chatButton release];
[super dealloc];
}

在(void)viewDidLoad方法中,我们需要添加一些通知观察器,以便我们可以看到键盘显示或隐藏的时间以及用户按下键盘上的键时。

   - (void)viewDidLoad {
//设置键盘显示/隐藏时的通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow :)
name:UIKeyboardWillShowNotification
对象:无];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide :)
name:UIKeyboardWillHideNotification
object:nil];

//设置按键时的通知。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyPressed :)
name:UITextViewTextDidChangeNotification
object:nil];

//关闭滚动并设置字体详细信息。
chatBox.scrollEnabled = NO;
chatBox.font = [UIFont fontWithName:@Helveticasize:14];

[super viewDidLoad];
}

当在textview上设置焦点时,将显示键盘。因为文本视图和按钮都位于屏幕下方的viewForm中,所以键盘将会骑行并重新进行操作。所以我们要做的是调整viewTable的高度和viewForm的位置。我们通过以下方法执行此操作。

   - (void)keyboardWillShow:(NSNotification *)note {
//获取键盘大小和位置
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue:& keyboardBounds];

//得到高度,因为这是我们需要的主要值。
NSInteger kbSizeH = keyboardBounds.size.height;

//得到表/主框架的矩形
CGRect tableFrame = viewTable.frame;
tableFrame.size.height - = kbSizeH;

//获取表单框架的矩形
CGRect formFrame = viewForm.frame;
formFrame.origin.y - = kbSizeH;

//动画设置
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3f];

//使用新信息设置视图
viewTable.frame = tableFrame;
viewForm.frame = formFrame;

//提交动画
[UIView commitAnimations];
}

既然显示了键盘并且我们的视图已经调整,我们想要捕获用户输入的文本,看看我们是否需要对chatBox进行任何调整。幸运的是,我们可以使用CGSize对象,传递一些文本,并告诉对象我们想要约束文本的大小,我们可以计算得到高度。现在这是一个小试验和错误的地方。该行随着字体的大小而变化,您的CGSize对象的宽度将随着UITextview的宽度而变化,因此您必须进行一些实验。在下面的代码中使用12的值是我的chatBox的起始高度和基于我设置的字体的行高之间的高度差异。

   - (void)keyPressed:(NSNotification *)notification {
//获取文本块的大小,这样我们就可以使用我们的魔法
CGSize newSize = [chatBox.text
sizeWithFont:[UIFont fontWithName:@Helveticasize:14]
constrainedToSize:CGSizeMake(222,9999)
lineBreakMode:UILineBreakModeWordWrap];
NSInteger newSizeH = newSize.height;
NSInteger newSizeW = newSize.width;

//我将新尺寸输出到控制台
//所以我们可以看到发生了什么
NSLog(@NEW SIZE:%d X%d,newSizeW ,newSizeH);
if(chatBox.hasText)
{
//如果新聊天框的高度为
//低于90,我们可以设置高度
if(newSizeH< ; = 90)
{
[chatBox scrollRectToVisible:CGRectMake(0,0,1,1)animated:NO];

// chatbox
CGRect chatBoxFrame = chatBox.frame;
NSInteger chatBoxH = chatBoxFrame.size.height;
NSInteger chatBoxW = chatBoxFrame.size.width;
NSLog(@CHAT BOX SIZE:%d X%d,chatBoxW,chatBoxH);
chatBoxFrame.size.height = newSizeH + 12;
chatBox.frame = chatBoxFrame;

//表单视图
CGRect formFrame = viewForm.frame;
NSInteger viewFormH = formFrame.size.height;
NSLog(@FORM VIEW HEIGHT:%d,viewFormH);
formFrame.size.height = 30 + newSizeH;
formFrame.origin.y = 199 - (newSizeH - 18);
viewForm.frame = formFrame;

//表格视图
CGRect tableFrame = viewTable.frame;
NSInteger viewTableH = tableFrame.size.height;
NSLog(@TABLE VIEW HEIGHT:%d,viewTableH);
tableFrame.size.height = 199 - (newSizeH - 18);
viewTable.frame = tableFrame;
}

//如果我们的新高度大于90
//设置不设置高度或移动
//并且启用滚动
if(newSizeH> 90)
{
chatBox.scrollEnabled = YES;
}
}
}

一旦我们和用户按下我们想要对我们的文本执行某些操作的发送按钮,关键字将消失,我们希望重新设置我们的视图。那么我们该怎么做?

   - (IBAction)chatButtonClick:(id)sender {
//隐藏键盘,我们完成了它。
[chatBox resignFirstResponder];
chatBox.text = nil;

// chatbox
CGRect chatBoxFrame = chatBox.frame;
chatBoxFrame.size.height = 30;
chatBox.frame = chatBoxFrame;
//表单视图
CGRect formFrame = viewForm.frame;
formFrame.size.height = 45;
formFrame.origin.y = 415;
viewForm.frame = formFrame;

//表格视图
CGRect tableFrame = viewTable.frame;
tableFrame.size.height = 415;
viewTable.frame = tableFrame;
}

resignFirstResponder将隐藏键盘然后我们所要做的就是将视图和聊天框设置回其原始状态。

   - (void)keyboardWillHide:(NSNotification *)note {
//获取键盘大小和位置

CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue:& keyboardBounds];

//得到高度,因为这是我们需要的主要值。
NSInteger kbSizeH = keyboardBounds.size.height;

//得到表/主框架的矩形
CGRect tableFrame = viewTable.frame;
tableFrame.size.height + = kbSizeH;

//获取表单框架的矩形
CGRect formFrame = viewForm.frame;
formFrame.origin.y + = kbSizeH;

//动画设置
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3f];

//使用新信息设置视图
viewTable.frame = tableFrame;
viewForm.frame = formFrame;

//提交动画
[UIView commitAnimations];
}

然后你去了,一个以单行开头的文本视图并且增长大小,因为用户在成为滚动文本视图之前将文本输入到最大大小。


Possible Duplicate:
How to create a multiline UITextfield?

How can I implement a multiple line textfield like what I see in the iPhone messaging app?

It seems like the once the length of input exceeds the length, a second line will be auto created.

EDIT: Updated to clarify my challenges in using a UITextView

For me, I would like to model the feel and look of the UITextView to that as shown below. I am not sure how I can do it with UITextView as suggested. For example

1) How to expand the box dynamically if my text needs to overflow to next line

2) How to add the border and styling as shown below

3) How to attach the text box right above the keyboard (instead of in the view)

I know that Instagram have this as well, if someone can point me to the correct direction, that will be great. Thanks in advnce

解决方案

Check these answers:

How to create a multiline UITextfield?

How to create a multiline UITextfield?

http://brettschumann.com/blog/2010/01/15/iphone-multiline-textbox-for-sms-style-chat

And definitly try Three20 which is a great library used in many app like Facebook.


Edit: Added extract from BrettSchumann blog

#import <uikit uikit.h="">
@interface MultilineTextboxViewController : UIViewController {
    IBOutlet UIView *viewTable;
    IBOutlet UIView *viewForm;
    IBOutlet UITextView *chatBox;
    IBOutlet UIButton   *chatButton;
}

@property (nonatomic, retain) UIView *viewTable;
@property (nonatomic, retain) UIView *viewForm;
@property (nonatomic, retain) UITextView *chatBox;
@property (nonatomic, retain) UIButton *chatButton;

- (IBAction)chatButtonClick:(id)sender;
@end
</uikit>

With that done and while we are setting everything up lets go and add our items to our main (.m) file at the same time not forgetting to de-allocate them as well.

@synthesize viewTable;
@synthesize viewForm;
@synthesize chatBox;
@synthesize chatButton;

- (void)dealloc{
    [viewTable release];
    [viewForm release];
    [chatBox release];
    [chatButton release];
    [super dealloc];
}

In the (void)viewDidLoad method we need to add some notification observers so that we can see when the keyboard is shown or hidden and when the user presses a key on the keyboard.

- (void)viewDidLoad {
    //set notification for when keyboard shows/hides
    [[NSNotificationCenter defaultCenter] addObserver:self 
                        selector:@selector(keyboardWillShow:) 
                        name:UIKeyboardWillShowNotification 
                        object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                        selector:@selector(keyboardWillHide:) 
                        name:UIKeyboardWillHideNotification 
                        object:nil];

    //set notification for when a key is pressed.
    [[NSNotificationCenter defaultCenter] addObserver:self 
                        selector: @selector(keyPressed:) 
                        name: UITextViewTextDidChangeNotification 
                        object: nil];

    //turn off scrolling and set the font details.
    chatBox.scrollEnabled = NO;
    chatBox.font = [UIFont fontWithName:@"Helvetica" size:14]; 

    [super viewDidLoad];
}

When focus is set on the textview the keyboard will be shown. Because the textview and buttons are both in the lower viewForm on the screen, the keyboard is going to ride up and go over these. So what we want to do is adjust the height of viewTable and the position of viewForm. We do this in the following method.

-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loction
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];

    // get the height since this is the main value that we need.
    NSInteger kbSizeH = keyboardBounds.size.height;

    // get a rect for the table/main frame
    CGRect tableFrame = viewTable.frame;
    tableFrame.size.height -= kbSizeH;

    // get a rect for the form frame
    CGRect formFrame = viewForm.frame;
    formFrame.origin.y -= kbSizeH;

    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // set views with new info
    viewTable.frame = tableFrame;
    viewForm.frame = formFrame;

    // commit animations
    [UIView commitAnimations];
}

Now that the keyboard is shown and our views have been adjusted we want to capture the text the user is entering and see if we need to make any adjustments to the chatBox. Lucky for us we can use the CGSize object, pass it some text, and tell the object what size we would want to constrain the text to and from that we can calculate get height.Now this is where a little trial and error comes in. The line varies with the size of the font and your width of your CGSize object will vary with the width of your UITextview so you will have to experiment a little. The value of 12 use in the code below is the difference in height between the starting height of my chatBox and the line height based on the font that I have set.

-(void) keyPressed: (NSNotification*) notification{
    // get the size of the text block so we can work our magic
    CGSize newSize = [chatBox.text 
                sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] 
                constrainedToSize:CGSizeMake(222,9999) 
                lineBreakMode:UILineBreakModeWordWrap];
    NSInteger newSizeH = newSize.height;
    NSInteger newSizeW = newSize.width;

    // I output the new dimensions to the console 
    // so we can see what is happening
    NSLog(@"NEW SIZE : %d X %d", newSizeW, newSizeH);
    if (chatBox.hasText)
    {
        // if the height of our new chatbox is
        // below 90 we can set the height
        if (newSizeH <= 90)
        {
            [chatBox scrollRectToVisible:CGRectMake(0,0,1,1) animated:NO];

            // chatbox
            CGRect chatBoxFrame = chatBox.frame;
            NSInteger chatBoxH = chatBoxFrame.size.height;
            NSInteger chatBoxW = chatBoxFrame.size.width;
            NSLog(@"CHAT BOX SIZE : %d X %d", chatBoxW, chatBoxH);
            chatBoxFrame.size.height = newSizeH + 12;
            chatBox.frame = chatBoxFrame;

            // form view
            CGRect formFrame = viewForm.frame;
            NSInteger viewFormH = formFrame.size.height;
            NSLog(@"FORM VIEW HEIGHT : %d", viewFormH);
            formFrame.size.height = 30 + newSizeH;
            formFrame.origin.y = 199 - (newSizeH - 18);
            viewForm.frame = formFrame;

            // table view
            CGRect tableFrame = viewTable.frame;
            NSInteger viewTableH = tableFrame.size.height;
            NSLog(@"TABLE VIEW HEIGHT : %d", viewTableH);
            tableFrame.size.height = 199 - (newSizeH - 18);
            viewTable.frame = tableFrame;
        }

        // if our new height is greater than 90
        // sets not set the height or move things
        // around and enable scrolling
        if (newSizeH > 90)
        {
            chatBox.scrollEnabled = YES;
        }
    }
}

Once we are and the user presses the send button we want to do something with our text, the keyword will disappear and we want to reset our view back as they were. So how do we do that?

- (IBAction)chatButtonClick:(id)sender{
    // hide the keyboard, we are done with it.
    [chatBox resignFirstResponder];
    chatBox.text = nil;

    // chatbox
    CGRect chatBoxFrame = chatBox.frame;
    chatBoxFrame.size.height = 30;
    chatBox.frame = chatBoxFrame;
    // form view
    CGRect formFrame = viewForm.frame;
    formFrame.size.height = 45;
    formFrame.origin.y = 415;
    viewForm.frame = formFrame;

    // table view
    CGRect tableFrame = viewTable.frame;
    tableFrame.size.height = 415;
    viewTable.frame = tableFrame;
}

The resignFirstResponder is going to hide the keyboard and then all we have to do is set the views and chatBox back to their original states.

-(void) keyboardWillHide:(NSNotification *)note{
    // get keyboard size and loction

    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];

    // get the height since this is the main value that we need.
    NSInteger kbSizeH = keyboardBounds.size.height;

    // get a rect for the table/main frame
    CGRect tableFrame = viewTable.frame;
    tableFrame.size.height += kbSizeH;

    // get a rect for the form frame
    CGRect formFrame = viewForm.frame;
    formFrame.origin.y += kbSizeH;

    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // set views with new info
    viewTable.frame = tableFrame;
    viewForm.frame = formFrame;

    // commit animations
    [UIView commitAnimations];
}

And there you go, a textview that starts off as a single line and grows in size as the user enters text to a max size before becoming a scrolling textview.

这篇关于目标C:如何创建多行UITextField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆