自定义标签导航项不起作用 - Swift

时间:2015-12-04 09:22:24

标签: ios swift uilabel uinavigationitem

我宣布了两个变量:

var myString:NSString = "NavigationItemTitle"
var myMutableString = NSMutableAttributedString()

接下来,在viewDidLoad()方法中:

 self.myMutableString = NSMutableAttributedString(string: self.myString as String, attributes: [NSFontAttributeName:UIFont(name: "Avenir", size: 18.0)!])
 self.myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:0,length:1))
 let label:UILabel = UILabel()
 label.attributedText = self.myMutableString
 self.navbar.topItem?.titleView = label

结果是我看不到导航项,只是一个空的导航栏。 我怀疑标题视图的最后一行有问题,因为当我测试这样的东西时:

self.navbar.topItem?.title = "foo"

导航项目可见,但我无法以这种方式应用任何格式。

如何修复我的代码,以便导航项显示为自定义标签?

3 个答案:

答案 0 :(得分:3)

UILabelUIView子类,UIView指定的初始化程序是`initWithFrame:。

通过使用UILabel()初始化标签,标签没有框架,因此无法显示。而是将此行替换为:

let label:UILabel = UILabel(frame: CGRectMake(0, 0, 200, 40))

(宽度任意设定,高度在44px高的导航栏上正常工作)

答案 1 :(得分:1)

请尝试以下代码。

类ViewController:UIViewController {

var myString:NSString = "NavigationItemTitle"
var myMutableString = NSMutableAttributedString()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.myMutableString = NSMutableAttributedString(string: self.myString as String, attributes: [NSFontAttributeName:UIFont(name: "Avenir", size: 18.0)!])
   self.myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:0,length:1))

    let titleLabel = UILabel(frame: CGRectMake(0, 0, view.frame.size.width - 120, 44))
    titleLabel.attributedText = self.myMutableString
    titleLabel.backgroundColor = UIColor.clearColor()
    titleLabel.textAlignment = NSTextAlignment.Center

    self.navigationController!.navigationBar.topItem!.titleView = titleLabel
    }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

需要设置UILabel的宽度。

  

let titleLabel = UILabel(frame:CGRectMake(0,0,view.frame.size.width)    - 120,44))

答案 2 :(得分:1)

是的,如果您添加任何需要为其设置框架的子视图

    let label:UILabel = UILabel(frame: CGRectMake(0, 0, 200, 40))