UISegmentedController中的图标和文本

Ben*_*nmj 8 iphone cocoa-touch ios

一个片段只能有图像或标题; 它不能兼得.没有默认图像.

所以在UISegmentedController Reference中说Apple .

有没有人想出一个通用的解决方案,让你同时拥有一个图标和文字?我有一个分段控件,有四个段.有自定义控件外观的选项,但它们似乎只为具有两个段的UISegmentedControl设计?

我正在努力的想法:

  1. 抛弃四个UIButton的分段控件并自行处理"选定"状态
  2. 举起我的手,只需要用文字图标.
  3. 你的建议...?

Dav*_*d H 10

您可以通过将当前图像绘制到上下文中来创建新图像,绘制所需文本,然后将该组合图像用作单段图像:

UIGraphicsBeginImageContextWithOptions(size, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();

// Text first
[myString drawAtPoint:somePoint withFont:font];

// Images upside down so flip them 
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, size.height);
CGContextConcatCTM(context, flipVertical);
CGContextDrawImage(context, (CGRect){ imagePoint, imageSize }, [myUIimage CGImage]);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的代码片段.我把它变成了[UIImage类别](https://gist.github.com/3801542),我发现它非常有用:[https://gist.github.com/3801542 ](https:/ /gist.github.com/3801542).它可以像这样使用`UIImage*image = [UIImage imageFromImage:uiImage] string:@"string"color:[UIColor whiteColor]];` (4认同)

Mik*_*ahy 5

您可能想尝试第三方替代方案,例如STSegmentedControl(没有关系,但我已经使用过它,听起来它会为您提供所需的灵活性而无需从头开始).