2017-03-19 8 views
0

UINavigationにサイクルビューとラベルを追加したいと思います。UINavigationにUILabelsを追加する方法は?

if let navigationBar = self.navigationController?.navigationBar { 
     let firstFrame = CGRect(x: 300, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height) 
     let firstLabel = UILabel(frame: firstFrame) 
     firstLabel.text = "First" 

     navigationBar.addSubview(firstLabel) 

    } 

が、私はこのコードによって、二つの問題があります: 1.howが正しくx位置を設定するために、私はこのコードで私のUINavigationにラベルを設定することができます

enter image description here

:このような? (私は300の値を設定することをテストするが、この値は異なる画面サイズで異なる位置を示す) 2.このラベルにサイクル背景を設定するには?

+0

あなたは 'UINavigationItem'のドキュメントを見ましたか? – rmaddy

答えて

2

ビュー(赤丸)とラベル(数字16)の両方を、サブボタンとしてプログラムでバーボタン項目のボタンに追加できます。あなたは何をすべき

は次のとおりです。

  • は、そのViewControllerをにIBOutletとしてボタンを接続します

enter image description here

連結成分がUIButtonではなく、あることを確認しますUIBarButtonItem

ご覧のとおり、私はbtnMenuと呼んでいます。

  • あなたのビューを作成し(赤い円と番号ラベル)とbtnMenuに追加:

それはのようになります。

import UIKit 

class ViewController: UIViewController { 
    //... 

    @IBOutlet weak var btnMenu: UIButton! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     //... 

     // setup the red circle UIView 
     let redCircleView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) 
     redCircleView.backgroundColor = UIColor.red 
     redCircleView.layer.cornerRadius = view.frame.size.width/2 

     // setup the number UILabel 
     let label = UILabel(frame: CGRect(x: 4, y: 0, width: 20, height: 20)) 
     label.textColor = UIColor.white 
     label.font = UIFont.systemFont(ofSize: 10) 
     label.text = "16" 

     // adding the label into the red circle 
     redCircleView.addSubview(label) 

     // adding the red circle into the menu button 
     btnMenu.addSubview(redCircleView) 

     //... 
    } 

    //... 
} 

そして、それはそれです!

UIButtonあなたがそれ(add​Subview(_:​))にサブビューを追加できることを意味し、UIViewのサブクラスです。

出力:これは助け

enter image description here

希望。