我正在使用一个UISegmentedControl
内部UIToolBar
按钮。我不能使用 normal UIButtonBarItem
,因为我需要设置tintColor
并支持 iOS 4.3。所以我使用以下代码:
UISegmentedControl* searchButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"", nil]];
[searchButton setImage:[UIImage imageNamed:@"search_picto"] forSegmentAtIndex:0];
searchButton.momentary = YES;
searchButton.segmentedControlStyle = UISegmentedControlStyleBar;
searchButton.tintColor = [UIColor colorWithRed:0.27 green:0.60 blue:0.20 alpha:1.00];
[searchButton addTarget:self action:@selector(actionSearch:) forControlEvents:UIControlEventValueChanged];
这很好用,但是有没有办法在我的图像旁边有一个文本/标题?方法 setTitle: 删除图像。一定有别的办法...
谢谢你的帮助。
--
编辑:我决定将文本直接添加到UIImageView
这样的:
NSString* label = @"My Label";
UIImage* image = [self addText:label toImage:[UIImage imageNamed:@"icon"]];
[_segmentedControl insertSegmentWithImage:image atIndex:0 animated:NO];
[_segmentedControl setWidth:image.size.width + 10]; // add some margin on the right
- (UIImage *)addText:(NSString *)text toImage:(UIImage *)image {
UIFont* font = [UIFont boldSystemFontOfSize: 12];
CGSize expectedSize = [text sizeWithFont:font];
[self retinaAwareUIGraphicsBeginImageContext:CGSizeMake(image.size.width + expectedSize.width + 10, image.size.height)];
[image drawAtPoint: CGPointZero];
[[UIColor whiteColor] set];
[text drawAtPoint: CGPointMake(30, 2) withFont:font];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (void)retinaAwareUIGraphicsBeginImageContext:(CGSize) size {
CGFloat scale = -1.0;
if (scale<0.0) {
UIScreen *screen = [UIScreen mainScreen];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
scale = [screen scale];
}
else {
scale = 0.0;
}
}
if (scale>0.0) {
UIGraphicsBeginImageContextWithOptions(size, NO, scale);
}
else {
UIGraphicsBeginImageContext(size);
}
}