为什么LeftBarButtonItem没有出现在swift

时间:2016-05-18 08:03:54

标签: swift swift2 navigationbar

我有两个视图A和视图B.

从视图A到视图B,我不使用导航控制器,我使用performSegueWithIdentifier(),我不想使用导航控制器将视图A传递给视图B.

但是在视图B中,我想在导航栏中添加一个leftBarButtonItem(我已经为视图B嵌入了导航控制器),就像带箭头的后退按钮一样。

为了与系统实现100%相同的箭头后退。我使用NSMutableAttributedStringUIButton。代码如下:

let string = "< Retour" as NSString
var attributedString = NSMutableAttributedString(string: string as String)

let ArrowAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(20)]
let TextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(10)]

attributedString.addAttributes(ArrowAttributes, range: string.rangeOfString("<"))
attributedString.addAttributes(ArrowAttributes, range: string.rangeOfString(" Retour"))

let backbutton = UIButton(type: .Custom)
backbutton.addTarget(self, action: "back:", forControlEvents: .TouchUpInside)
backbutton.setAttributedTitle(attributedString, forState: UIControlState.Normal)
        self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(customView: backbutton), animated: true)
        rightBtn = UIBarButtonItem(title: "Ok", style: .Plain, target: self, action: "save:")

但我在视图B的导航栏中看不到左键...为什么我在导航栏中看不到它?为什么左键消失?

非常感谢。

我已经为标签尝试了新代码,但它还不起作用......

let barButtonBackStr = "< Back"
let attributedBarButtonBackStr = NSMutableAttributedString(string: barButtonBackStr as String)
attributedBarButtonBackStr.addAttribute(NSFontAttributeName,
                                                value: UIFont(
                                                    name: "AmericanTypewriter-Bold",
                                                    size: 18.0)!,
                                                range: NSRange(
                                                    location:0,
                                                    length:1))
let label = UILabel()
label.attributedText = attributedBarButtonBackStr
label.sizeToFit()
let newBackButton = UIBarButtonItem(customView: label)
        self.navigationController!.navigationItem.setLeftBarButtonItem(newBackButton, animated: true)

谢谢

2 个答案:

答案 0 :(得分:1)

试试<item name="%the_component_to_be_disabled%" xsi:type="array"> <item name="visible" xsi:type="boolean">false</item> </item> ,您会看到按钮

您创建了一个按钮,但您从未设置框架

您也可以直接设置框架,而不是像backbutton.sizeToFit()

这样的sizeToFit()方法

PS:backbutton.frame = CGRectMake(0, 0, 100, 20)未使用

答案 1 :(得分:0)

您必须将其写入:

override func viewDidAppear(animated: Bool) {
     super.viewDidAppear(animated)
     ...
}

尝试在UI设计之后设置断点,并尝试启动“调试视图层次结构”以查看按钮是否存在或是否被其他对象隐藏

enter image description here

接下来,在设置完按钮后尝试制作:

self.navigationController!.navigationItem.leftBarButtonItem.customView.sizeToFit()