ios 目标 C:如何创建多行 UITextField?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6398519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:25:12  来源:igfitidea点击:

Objective C: How to create a multi-line UITextField?

objective-ciosuitextfield

提问by Zhen

Possible Duplicate:
How to create a multiline UITextfield?

可能的重复:
如何创建多行 UITextfield?

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

如何实现多行文本字段,就像我在 iPhone 消息应用程序中看到的那样?

enter image description here

在此处输入图片说明

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

编辑:更新以澄清我在使用 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

对我来说,我想将 UITextView 的感觉和外观建模为如下所示。我不确定如何按照建议使用 UITextView 做到这一点。例如

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

1) 如果我的文本需要溢出到下一行,如何动态展开框

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

2)如何添加边框和样式如下图

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

3)如何将文本框附加在键盘正上方(而不是在视图中)

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

我知道 Instagram 也有这个,如果有人能指出我正确的方向,那就太好了。提前致谢

enter image description here

在此处输入图片说明

回答by Nicolas S

Check these answers:

检查这些答案:

How to create a multiline UITextfield?

如何创建多行 UITextfield?

How to create a multiline UITextfield?

如何创建多行 UITextfield?

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

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

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

并且一定要尝试Three20,这是一个很棒的库,在 Facebook 等许多应用程序中都使用过。



Edit: Added extract from BrettSchumann blog

编辑:添加了 BrettSchumann 博客的摘录

#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.

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

@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 方法中,我们需要添加一些通知观察者,以便我们可以看到键盘何时显示或隐藏以及用户何时按下键盘上的某个键。

- (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.

当焦点设置在 textview 上时,将显示键盘。因为 textview 和按钮都在屏幕上的下部 viewForm 中,所以键盘会骑上去并越过这些。所以我们要做的就是调整viewTable的高度和viewForm的位置。我们通过以下方法执行此操作。

-(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.

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

-(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.

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

-(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.

就这样,一个 textview 从一行开始,随着用户输入文本到最大大小,在变成滚动 textview 之前,它的大小会增加。

回答by mt81

UITextFielddoesn't let you to write more than one line... but you can use UITextViewinstead, and use the NSString -sizeWithFontfunction to understand how much space you need.

UITextField不会让你写多于一行……但你可以UITextView改用,并使用该NSString -sizeWithFont函数来了解你需要多少空间。

like this:

像这样:

CGSize size = [yourTextView.text sizeWithFont:yourTextView.font];
CGRect f = yourTextView.frame;
f.size.height = ceil(size.width/f.size.width)*size.height
yourTextView.frame = f;

I didn't tried this code, but I already used a code like that in the past. I hope my informations may be useful :)

我没有尝试过这个代码,但我过去已经使用过这样的代码。我希望我的信息可能有用:)