嵌入在导航控制器中的UINavigationBar - 添加自定义视图

时间:2014-10-17 01:58:46

标签: ios xcode uinavigationbar

我有一个嵌入在导航控制器中的UIView,因此我免费获得UINavigationBar。

我尝试做的是添加自定义视图。这可能/可取吗?我只是想用一些文字添加一个简单的视图。

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

您只需将自定义子视图添加到导航栏即可:

screenshot

Swift源代码示例

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

}