UITextView линейчатый фон, но неправильная высота строки

У меня есть UITextView, где пользователь может создавать заметки и сохранять в файл plist. Я хочу, чтобы показывать строки, как обычный ноутбук. Проблема в том, что текст не будет правильно выровнен.

Изображение ниже объясняет проблему достаточно хорошо.

Мой экран печати очень хорошо объясняет проблему

Это фон, который я использую для создания строк, таких как Notes.app введите описание изображения здесь

Это мой код для создания фона для моего UITextView :

 textView.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:19.0]; textView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed: @"Notes.png"]]; 

Я знаю, что свойство UIFont.lineHeight доступно только в> iOS 4.x.

Поэтому мне интересно, есть ли другое решение моей проблемы?

Вы должны попытаться рисовать свои линии программным способом, а не использовать изображение. Вот пример кода, как вы могли бы это сделать. Вы можете подclassифицировать UITextView и переопределить метод drawRect:

NoteView.h

 #import  @interface NoteView : UITextView  { } @end 

NoteView.m

 #import "NoteView.h" @implementation NoteView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor colorWithRed:1.0f green:1.0f blue:0.6f alpha:1.0f]; self.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:19]; } return self; } - (void)drawRect:(CGRect)rect { //Get the current drawing context CGContextRef context = UIGraphicsGetCurrentContext(); //Set the line color and width CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.2f].CGColor); CGContextSetLineWidth(context, 1.0f); //Start a new Path CGContextBeginPath(context); //Find the number of lines in our textView + add a bit more height to draw lines in the empty part of the view NSUInteger numberOfLines = (self.contentSize.height + self.bounds.size.height) / self.font.leading; //Set the line offset from the baseline. (I'm sure there's a concrete way to calculate this.) CGFloat baselineOffset = 6.0f; //iterate over numberOfLines and draw each line for (int x = 0; x < numberOfLines; x++) { //0.5f offset lines up line with pixel boundary CGContextMoveToPoint(context, self.bounds.origin.x, self.font.leading*x + 0.5f + baselineOffset); CGContextAddLineToPoint(context, self.bounds.size.width, self.font.leading*x + 0.5f + baselineOffset); } //Close our Path and Stroke (draw) it CGContextClosePath(context); CGContextStrokePath(context); } @end 

MyViewController.h

 #import  #import "NoteView.h" @interface MyViewController : UIViewController  { NoteView *note; } @property (nonatomic, retain) NoteView *note; @end 

MyViewController.m

 #import "MyViewController.h" #import "NoteView.h" #define KEYBOARD_HEIGHT 216 @implementation MyViewController @synthesize note; - (void)loadView { [super loadView]; self.note = [[[NoteView alloc] initWithFrame:self.view.bounds] autorelease]; [self.view addSubview:note]; note.delegate = self; note.text = @"This is the first line.\nThis is the second line.\nThis is the ... line.\nThis is the ... line.\nThis is the ... line.\nThis is the ... line.\nThis is the ... line.\n"; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [note setNeedsDisplay]; } - (void)textViewDidBeginEditing:(UITextView *)textView { CGRect frame = self.view.bounds; frame.size.height -= KEYBOARD_HEIGHT; note.frame = frame; } - (void)textViewDidEndEditing:(UITextView *)textView { note.frame = self.view.bounds; } - (void)dealloc { [note release]; [super dealloc]; } 

Взгляните на документацию Apple для управления клавиатурой , в частности «Перемещение содержимого, находящегося под клавиатурой». В нем объясняется, как слушать NSNotifcations и правильно корректировать ваши взгляды.

Я думаю, проблема связана с вашим изображением, желтое пространство над линией создает проблему.

Вы должны отредактировать изображение.

И приятная работа.

  • Типы в объективе-c на iPhone
  • API, чтобы определить, работает ли на iPhone или iPad
  • Выясните, нажал ли пользователь кнопку «Назад» в controllerе uinavigation?
  • Как отправить данные json в запрос Http с помощью NSURLRequest
  • Ошибка UIActivityViewController на iOS 8 iPads
  • Что такое хорошо для?
  • Расчет скорости соединения / загрузки
  • Можно ли отключить плавающие заголовки в UITableView с помощью UITableViewStylePlain?
  • UISlider вместе с ProgressView
  • Каков наилучший способ перетащить NSMutableArray?
  • Можете ли вы настраивать анимацию для встраиваемых ячеек UITableView?
  • Давайте будем гением компьютера.