views:

305

answers:

3

How do I put a template'd background image on a text area?

+6  A: 

Not sure what you mean with "template'd"... but....

In interface builder, add the imageview behind the textview, uncheck the "opaque" box for the textview.

wkw
Trying this now wkw! If it works your answer wins!
Daniel
How do you put an imageview behind the textview?
Daniel
You just drop an image view in, you might have to change the z order of the textview so that it is above the image view.
Ukko
A: 

If you want to add the image programmaticaly I managed to do it this way:

First in my textviewViewController.h I added an outlet for the UITextView.

#import <UIKit/UIKit.h>

@interface textviewViewController : UIViewController {
UITextView *textView;
}
@property (nonatomic, retain) IBOutlet UITextView *textView;

@end

Next, in my .xib I added my UITextView and connected my outlet.

Lastly in the viewDidLoad of textviewViewController.m I add the image as a subview to my textview.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Change the pathForResource to reflect the name and type of your image file
    NSString *path = [[NSBundle mainBundle] pathForResource:@"d" ofType:@"jpg"];
    UIImage *img = [UIImage imageWithContentsOfFile:path];

    UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
    [self.textView insertSubview:imgView atIndex:0];
    [imgView release];

}

I tried the insertSubview:atIndex: with both 0 and 1 with the same result, but I would stick with 0 idicating that it's behind the textview.

thelaws
`[self.textView insertSubview:imgView atIndex:0];` inserts the image into, not behind, the textView. Use `[[self.textView superview] insertSubview:imgView belowSubview:self.textView];` to put it behind the textView, assuming superview is not nil. The latter will not scroll with the text. And don't forget to release imgView after inserting it.
drawnonward
thanks drawnonward, you're right I forgot to release my imgView. Since this is in my view controller the imageView could be inserted into the main view with a [self.view insertSubview:] but I got the impression that the imageView was wanted as part of the textview.
thelaws
+4  A: 

You can set the contents property of the text views layer.

#import <QuartzCore/QuartzCore.h>

...

- (void) viewDidLoad {
    [super viewDidLoad];
    textView.layer.contents = (id)[UIImage imageNamed:@"myImage.png"].CGImage
}

should work

Elfred