0

I'm indenting the first line in a UITextView as you type. Here's a demo.

This works but I can't figure out how to have the text view indent when it appears. If you add and delete a character from the keyboard it indents the empty line correctly but I can't figure out how to do this when it first appears.

@interface ViewController ()
@property (strong, nonatomic) UITextView *textView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.textView = [UITextView new];
    self.textView.delegate = self;
    [self.view addSubview:self.textView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.textView.frame = self.view.bounds;
    [self textViewDidChange:self.textView];
}

- (void)textViewDidChange:(UITextView *)textView {  
    NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
    style.firstLineHeadIndent = 20.f;   
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:textView.text attributes:@{NSParagraphStyleAttributeName: style}];    
    textView.attributedText = string;
}
@end
Berry Blue
  • 15,330
  • 18
  • 62
  • 113

2 Answers2

0

I think this does the same job as that of your code.

textView.textContainerInset = UIEdgeInsetsMake(8.0f, 20.0f, 8.0f, 0.0f);
gabbler
  • 13,626
  • 4
  • 32
  • 44
0

If I understood correctly, you would like to have the cursor be indented when the user taps the empty UITextView to start typing, and at the moment it only starts to indent once the user starts to type.

In your viewDidLoad, initialise the attributedText with @" " and then set the text to @"" like this:

-(void)viewDidLoad 
{
    [super viewDidLoad];
    self.textView = [UITextView new];
    self.textView.delegate = self;
    [self.view addSubview:self.textView];

    NSMutableParagraphStyle* style = [NSMutableParagraphStyle new];
    style.firstLineHeadIndent = 20.f;   
    NSMutableAttributedString* string = [[NSMutableAttributedString alloc] initWithString:@" " attributes:@{NSParagraphStyleAttributeName: style}];    
    textView.attributedText = string;
    textView.text = @"";
}

Note: I think the code inside textViewDidChange is not necessary.

Bokoskokos
  • 512
  • 4
  • 13
  • 1
    Yes, but as I wrote in my comments for the other posted answer I can't change the value of the attributed text simple to trigger the attributes. I want the indent to occur when you first tap the text view with an empty string like it does when you insert and delete a character from the keyboard. – Berry Blue Jan 06 '15 at 23:05