Iphone – A word-wrapping text field with an image background on the iPhone

iphoneiphone-sdk-3.0uikit

Does anyone know how to create a text field that has a UIImage background and does word-wrapping?

It appears that word-wrapping is not available on UITextField, while a background image is not available for UITextView! Also, it should change the size of the control or at least alert that the number of lines changed so that a delegate could change its size..

An example of such control is the input field for messages in the SMS application.

Edit: the code should also get the text field to always show the text being edited. Apparently, when UITextView changes size while editing it somehow loses focus on the current text.

Thanks ahead!
Aviad.

Best Answer

Word-wrapping is not available on UITextField because UITextField only supports single-line text.

Use a UITextView. Make textView.backgroundColor = [UIColor clearColor]. Add the UIImage first, then the UITextView on top of it. Make sure the sizes are correct, and you should be fine.

As for changing the size of the UITextView, in your UITextViewDelegate, do something like this:

- (void)textViewDidChange:(UITextView *)textView
{
    NSString *s = textView.text;
    CGSize testSize = CGSizeMake(textView.frame.size.width, NSIntegerMax);
    CGSize neededSize = [s sizeWithFont: textView.font constrainedToSize: testSize     lineBreakMode: UILineBreakModeWordWrap]; // or UILineBreakModeCharacterWrap?

    if (neededSize.height > testSize.height)
    {
        // grow textView
        textView.frame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y, neededSize.width, neededSize.height);

        // then adjust the image size -- something like this
        imageView.frame = textView.frame 
    }

}