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

Custom label navigation item does not work - Swift

我声明了两个变量:

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"

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

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

UILabel是一个UIView子类,并且UIView指定初始化器是`initWithFrame:.

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

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

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

请尝试以下代码。

class 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))

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

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