Question

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.

Was it helpful?

Solution

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 
    }

}

OTHER TIPS

Eventually I wrote my own code, which worked to some degree with a lot of workarounds (changing the focus for example, resizing when removing all the text again, etc). If anyone's interested, I'll post the code.

In other news, just today I saw in a different question around here something called IFVerticallyExpandingTextField. The name was promising, the code is here, and I'll give it a look. Anyone with a similar problem, you might want to see this too.

My mistake, I didn't read it carefully enough: IFVerticallyExpandingTextField is for the Mac, not the iPhone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top