为什么编程创建(底部)工具栏按钮标题不显示?

时间:2017-07-24 18:45:40

标签: ios swift uibarbuttonitem uitoolbar

在Swift 3中,我以编程方式创建了一个(底部)工具栏,其中自定义按钮由一个灵活的间隔分隔开,以分隔自定义按钮,将一个("上一个")推到左边缘,另一个("下一个")到视图的右边缘。但是我无法显示按钮标题("上一个"和#34;下一个")。请建议我。谢谢。这是我的代码:

首先,类声明和一些变量:

class TextsController: UIViewController,UIGestureRecognizerDelegate {

let textWebView = WKWebView(frame: .zero)
var toolbar:UIToolbar?

接下来,在viewDidLoad:

    view = textWebView

    // Create (bottom) toolbar:
    let frame = CGRect(x: 0, y: UIScreen.main.bounds.size.height-44, width: UIScreen.main.bounds.size.width, height: 44)
    toolbar = UIToolbar(frame: frame)
    toolbar?.sizeToFit()
    toolbar?.isHidden = true
    self.view.addSubview(toolbar!)
    self.toolbar?.isTranslucent = false // Required for setting tintColor & barTintColor below

    toolbar?.tintColor = UIColor(red: 0.5, green: 0.0, blue: 1.0, alpha: 1.0) //purple for toolbar items
    toolbar?.barTintColor = UIColor.white //white for toolbar color

    let triangleLeftButton = UIBarButtonItem(image: UIImage(named: "triangleLeft_15x20"), style: .plain, target: self, action:#selector(showPrevious))
    let flexibleSpacer = UIBarButtonItem(barButtonSystemItem:.flexibleSpace , target: self, action: nil)
    let triangleRightButton = UIBarButtonItem(image: UIImage(named: "triangleRight_15x20"), style: .plain, target: self, action:#selector(showNext))

    triangleLeftButton.title = "Previous"
    triangleRightButton.title = "Next"

    var items = [UIBarButtonItem]()
    items.append(triangleLeftButton)
    items.append(flexibleSpacer)
    items.append(triangleRightButton)
    toolbar?.items = items

2 个答案:

答案 0 :(得分:0)

自定义视图或图片栏按钮项目没有标题。条形按钮项 标题自定义视图图像。如果您希望某些单词出现在自定义视图或图像栏按钮项中,请将这些单词作为自定义视图或图像的一部分。

答案 1 :(得分:0)

以下是我解决这个问题的方法。

我删除了试图为每个按钮分配标题的两个语句(我不知道为什么Xcode没有标记,允许我最初为每个标题分配一个标题,尽管两个标题都不会显示)。

我重写了(比较下面的代码和问题中的代码)UIBarButtonItems如下所示,现在包括两个文本项:

    // Create toolbar items (buttons and texts)
    let triangleLeftButton = UIBarButtonItem(image: UIImage(named: "triangleLeft_15x20"), style: .plain, target: self, action:#selector(showPrevious))
    let triangleLeftText = UIBarButtonItem(title: "Previous", style: .plain, target: nil, action: nil)
    let flexibleSpacer = UIBarButtonItem(barButtonSystemItem:.flexibleSpace , target: self, action: nil)
    let triangleRightText = UIBarButtonItem(title: "Next", style: .plain, target: nil, action: nil)
    let triangleRightButton = UIBarButtonItem(image: UIImage(named: "triangleRight_15x20"), style: .plain, target: self, action:#selector(showNext))

然后我将所有内容(包括两个新文本项)附加到数组中:

    var items = [UIBarButtonItem]()
    items.append(triangleLeftButton)
    items.append(triangleLeftText)
    items.append(flexibleSpacer)
    items.append(triangleRightText)
    items.append(triangleRightButton)
    toolbar?.items = items

这有效地放置了" Previous"与左指点按钮相邻,"下一步"靠近右指向按钮,柔性垫片之间有很大的间隙。