8

我有一个UITabBar但我不想设置我只想设置标题的图像,我希望这个标题垂直对齐。这可能吗?

谢谢

4

3 回答 3

5

从来没听说过。我认为您需要创建文本标签的图像(提前在您选择的图形工具中,或者您可以在运行时以编程方式创建它们)。

如果您想以编程方式执行此操作,则可以使用以下方法。它使用您传递的文本创建一个居中对齐的图像,执行自动换行。

UITabBarItem *item = [self.tabBar.items objectAtIndex:0];
item.image = [self makeThumbnailFromText:@"Tab Bar One"];
item.title = nil;

item = [self.tabBar.items objectAtIndex:1];
item.image = [self makeThumbnailFromText:@"Tab Bar Two"];
item.title = nil;

这使用了一种通过渲染传递给它的文本来创建位图的小方法。您可能必须使用图像大小和字体大小来优化您的标签栏控制器图像。

- (UIImage *)makeThumbnailFromText:(NSString *)string {
    // some variables that control the size of the image we create, what font to use, etc.

    CGSize imageSize = CGSizeMake(60, 80);
    CGFloat fontSize = 13.0;
    NSString *fontName = @"Helvetica-Bold";
    UIFont *font = [UIFont fontWithName:fontName size:fontSize];
    CGFloat lineSpacing = fontSize * 1.2;

    // set up the context and the font

    UIGraphicsBeginImageContextWithOptions(imageSize, false, 0);
    NSDictionary *attributes = @{NSFontAttributeName: font};

    // some variables we use for figuring out the words in the string and how to arrange them on lines of text

    NSArray <NSString *> *words = [string componentsSeparatedByString:@" "];
    NSMutableArray <NSDictionary *> *lines = [NSMutableArray array];
    NSString *lineThusFar;
    CGSize sizeThusFar = CGSizeZero;

    // let's figure out the lines by examining the size of the rendered text and seeing whether it fits or not and
    // figure out where we should break our lines (as well as using that to figure out how to center the text)

    for (NSString *word in words) {
        NSString *currentLine = lineThusFar ? [NSString stringWithFormat:@"%@ %@", lineThusFar, word] : word;
        CGSize size = [currentLine sizeWithAttributes: attributes];
        if (size.width > imageSize.width && lineThusFar) {
            [lines addObject:@{@"text": lineThusFar, @"size": [NSValue valueWithCGSize: sizeThusFar]}];
            lineThusFar = word;
            sizeThusFar = [word sizeWithAttributes: attributes];
        } else {
            lineThusFar = currentLine;
            sizeThusFar = size;
        }
    }
    if (lineThusFar) {
        [lines addObject:@{@"text": lineThusFar, @"size": [NSValue valueWithCGSize: sizeThusFar]}];
    }

    // now write the lines of text we figured out above

    CGFloat totalSize = (lines.count - 1) * lineSpacing + fontSize;
    CGFloat topMargin = (imageSize.height - totalSize) / 2.0;

    for (NSInteger i = 0; i < lines.count; i++) {
        CGFloat x = (imageSize.width - [lines[i][@"size"] CGSizeValue].width) / 2.0;
        CGFloat y = topMargin + i * lineSpacing;
        [lines[i][@"text"] drawAtPoint:CGPointMake(x, y) withAttributes: attributes];
    }

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

    return image;
}

在 Swift 中,这可能看起来像:

func makeThumbnailFromText(text: String) -> UIImage {
    // some variables that control the size of the image we create, what font to use, etc.

    struct LineOfText {
        var string: String
        var size: CGSize
    }

    let imageSize = CGSize(width: 60, height: 80)
    let fontSize: CGFloat = 13.0
    let fontName = "Helvetica-Bold"
    let font = UIFont(name: fontName, size: fontSize)!
    let lineSpacing = fontSize * 1.2

    // set up the context and the font

    UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
    let attributes = [NSFontAttributeName: font]

    // some variables we use for figuring out the words in the string and how to arrange them on lines of text

    let words = text.componentsSeparatedByString(" ")
    var lines = [LineOfText]()
    var lineThusFar: LineOfText?

    // let's figure out the lines by examining the size of the rendered text and seeing whether it fits or not and
    // figure out where we should break our lines (as well as using that to figure out how to center the text)

    for word in words {
        let currentLine = lineThusFar?.string == nil ? word : "\(lineThusFar!.string) \(word)"
        let size = currentLine.sizeWithAttributes(attributes)
        if size.width > imageSize.width && lineThusFar != nil {
            lines.append(lineThusFar!)
            lineThusFar = LineOfText(string: word, size: word.sizeWithAttributes(attributes))
        } else {
            lineThusFar = LineOfText(string: currentLine, size: size)
        }
    }
    if lineThusFar != nil { lines.append(lineThusFar!) }

    // now write the lines of text we figured out above

    let totalSize = CGFloat(lines.count - 1) * lineSpacing + fontSize
    let topMargin = (imageSize.height - totalSize) / 2.0

    for (index, line) in lines.enumerate() {
        let x = (imageSize.width - line.size.width) / 2.0
        let y = topMargin + CGFloat(index) * lineSpacing
        line.string.drawAtPoint(CGPoint(x: x, y: y), withAttributes: attributes)
    }

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}

var item = tabBar.items![0]
item.image = makeThumbnailFromText("Tab Bar One")
item.title = nil;

item = tabBar.items![1]
item.image = makeThumbnailFromText("Tab Bar Two")
item.title = nil;
于 2012-06-28T16:46:13.397 回答
1

对于迅捷3

//我的中心项目仅是图像,其余选项卡栏项目仅是文本

 let tabs = CustomTabBarController();
 tabs.viewControllers = [ViewControllerOne(),ViewControllerTwo(),ViewControllerThree()]

    let tabbar = tabs.tabBar;
    tabbar.backgroundColor = UIColor.white

    let tabOne = tabbar.items![0]
    tabOne.title = "One"

    let tabTwo = tabbar.items![1]
    tabTwo.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
    tabTwo.image = UIImage(named: "tab_icon.png")

    let tabThree = tabbar.items![2]
    tabThree.title = "Three"

//在我的CustomTabBarController中

 import UIKit

 class CustomTabBarController: UITabBarController {

override func viewDidLoad() {
    super.viewDidLoad()

    UITabBar.appearance().tintColor = UIColor.black
      UITabBarItem.appearance().titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -15)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    self.selectedIndex = 1;
}

override var selectedViewController: UIViewController? {
    didSet {

        guard let viewControllers = viewControllers else {
            return
        }

        for viewController in viewControllers {

            if viewController == selectedViewController {

                let selected: [String: AnyObject] =
                    [NSFontAttributeName:fontForTimesRoman(withStyle: "bold", andFontsize: 12),
                     NSForegroundColorAttributeName: UIColor.black]

                viewController.tabBarItem.setTitleTextAttributes(selected, for: .normal)

            } else {

                let normal: [String: AnyObject] =
                    [NSFontAttributeName: fontForTimesRoman(withStyle: "regular", andFontsize: 12),
                     NSForegroundColorAttributeName: UIColor.gray]

                viewController.tabBarItem.setTitleTextAttributes(normal, for: .normal)

              }
           }
       }
   }


   func fontForTimesRoman(withStyle style: String, andFontsize size: CGFloat) -> UIFont {
if (style == "bold") {
    return UIFont(name: "TimesNewRomanPS-BoldMT", size: size)!
}
else if(style == "italic"){
    return UIFont(name: "TimesNewRomanPS-ItalicMT", size: size)!
}
else{
    return UIFont(name: "TimesNewRomanPSMT", size: size)!
  }

  }
  }
于 2017-08-28T05:35:48.967 回答
0

要在 Xcode 10 和 swift 12 中隐藏标签栏项目图标/图像,请选择标签栏项目,然后:

1)显示属性检查器
2)将“系统项目”设置为“自定义”
3)让“选定图像”和属性为空
4) 让“Bar Item -> Image”属性为空

隐藏即可。
我还不知道如何垂直对齐,但如果我发现如何做到这一点,我会回来补充答案。
查看链接上提到的图片: 我只能在标签栏项目中显示文本并更改样式和位置

于 2019-04-23T15:59:29.040 回答