我在UIToolBar
內使用UISegmentedControl
作爲按鈕。我不能使用正常的UIButtonBarItem
,因爲我需要設置tintColor
並支持iOS 4.3。 所以我用下面的代碼:帶圖像和標題的UISegmentedControl
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);
}
}
而你在哪裏設置標題?我不認爲你理解我的問題... –
我不認爲這是可能的。該文檔說明如下: 分段控件可以顯示標題(NSString對象)或圖像(UIImage對象)。 如果你想設置標題: [searchButton insertSegmentWithTitle:@「Up」atIndex:0 animated:NO]; [searchButton insertSegmentWithTitle:@「Down」atIndex:1 animated:NO]; –