aherrick
aherrick

Reputation: 20161

UINavigationBar in View Embedded in Navigation Controller - Add Custom View

I have a UIView that is embedded in a Navigation Controller, so I get the UINavigationBar for free.

What I'm trying to do is add append a custom view to it. Is this possible/desirable? I just want to add a simple view with some text.

enter image description here enter image description here

Upvotes: 0

Views: 565

Answers (1)

Zhang
Zhang

Reputation: 11607

You can simply add a custom subview to your navigation bar:

screenshot

Swift Source Code Example

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    self.navigationItem.title = "Demo App";

    self.view.backgroundColor = UIColor.whiteColor();

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "compose");


    var notificationView:UIView = UIView(frame: CGRectMake(20, 50, self.view.bounds.size.width - 40.0, 50.0));
    notificationView.backgroundColor = UIColor(red: 145.0/255.0, green: 45.0/255.0, blue: 37.0/255.0, alpha: 1.0);
    notificationView.layer.cornerRadius = 8.0;
    notificationView.layer.shadowColor = UIColor.blackColor().CGColor;
    notificationView.layer.shadowOpacity = 0.25;
    notificationView.layer.shadowRadius = 2.0;
    notificationView.layer.shadowOffset = CGSizeMake(0, 3);

    var messageLabel:UILabel = UILabel(frame: CGRectMake(0, 0, notificationView.frame.size.width, notificationView.frame.size.height));
    messageLabel.text = "Error: text fields cannot be empty";
    messageLabel.textColor = UIColor.whiteColor();
    messageLabel.textAlignment = NSTextAlignment.Center;

    notificationView.addSubview(messageLabel);

    self.navigationController?.navigationBar.addSubview(notificationView);

}

Upvotes: 1

Related Questions