Первая проблема: я использую родительское представление с 415 пикселями, потому что 45 (460-415) взяты панелью навигации.Не нужно подталкивать, так как я начинаю с 415.
Второй и третий: не совсем.Вы можете использовать растягиваемое изображение, где вы рисуете текст.Для этого рецепта вам понадобится кнопка с левой и правой стороной и один пиксель посередине, который будет растянут до размера (левая сторона + правая сторона + длина текста посередине).
Пример: левая кнопка с 12 + 1 + (размер текста) + 5 пикселей
![left button](https://i.stack.imgur.com/1W9Ky.png)
Затем сделайте это:
/**
* Return the given image with white text written in the middle.
*
* The image should be stretchable.
* The text is written with bold system font 12.
*
* @param btnLeft The original image.
* @param capWidth The capWidth to stretch it.
* @param text The text to draw in the image.
* @return A image containing the original stretched image with some text written in the middle.
*/
+(UIImage*) drawText:(NSString*)text inImage:(UIImage*)image capWidth:(int)capWidth {
if (image==nil) {
return nil;
}
// make it stretchable
UIImage *stretchable = [image stretchableImageWithLeftCapWidth: capWidth
topCapHeight: 0];
UIFont *font = [UIFont boldSystemFontOfSize:12];
// the combined size is that of the image plus the text
CGSize textSize = [text sizeWithFont:font];
CGSize combinedSize = CGSizeMake(image.size.width + textSize.width, image.size.height); // should be +4 for more breath
UIGraphicsBeginImageContext(combinedSize);
// draw the image
[stretchable drawInRect:CGRectMake(0,0,combinedSize.width,combinedSize.height)];
// draw the text
float y = (image.size.height-textSize.height)/2; // leaves even distance to top and bottom
CGRect rect = CGRectMake(capWidth, y, textSize.width,textSize.height); // should be +2 for more breath space
[[UIColor whiteColor] set];
[text drawInRect:CGRectIntegral(rect) // positioning on a fractional point produces blurry text
withFont:font];
// gets the result
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Обратите внимание, что я использую системный шрифт, если вы хотите что-то другое, добавьте еще один параметр.А затем вы добавляете следующее в viewLoad вашего контроллера:
// buttonLeft is the button UIImage
UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [ImageUtils drawText:@"Back" inImage:buttonLeft capWidth:14];
[back setBackgroundImage:image forState:UIControlStateNormal];
[back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
back.frame = CGRectMake(0, 0, image.size.width, image.size.height);
UIBarButtonItem *backbi = [[[UIBarButtonItem alloc] initWithCustomView:back] autorelease];
self.navigationItem.leftBarButtonItem = backbi;
Что мы достигаем с помощью этого кода?кнопки идеального размера, которые работают с любой локализованной строкой, и избавляют вас от создания 2x PNG (обычный + сетчатка) для каждого поддерживаемого языкаЭто похоже на код Core Graphics, который UIKit использует для рисования кнопок с заголовком, поэтому он не замедлит ваш пользовательский интерфейс.