Search code examples
objective-cswiftuitoolbaruibarmetricsuitoolbarposition

Setting UIToolBar Background image swift


I am using swift to make an IOS application. I have a UIToolBar in my application and I need to change its background. I use the following code in Objective-C to do that:

[topBar setBackgroundImage:[UIImage imageNamed:@"header_bg.png"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];

Now when I rewrote the code in swift it looks like this:

topBar.setBackgroundImage(UIImage(named:"header_bg.png"), forToolbarPosition: UIToolbarPositionAny, barMetrics: UIBarMetricsDefault)

And this showed the errors that Use of unresolved type UIBarMetricsDefault and Use of unresolved type UIToolbarPositionAny. So I did a search and found this documentation. According to the documentation I changed the code like this:

topBar.setBackgroundImage(UIImage(named:"header_bg.png"), forToolbarPosition: Any, barMetrics: Default)

But it still shows the same error. Anyone got any idea what is wrong here?


Solution

  • Enums are done a little differently in Swift. For example, instead of saying: UIBarMetricsDefault, you say .Default. So, your code should look like this:

    topBar.setBackgroundImage(UIImage(named:"header_bg.png"), forToolbarPosition: .Any, barMetrics: .Default)
    

    I recommend you look at the "Introduction to Swift" document on http://developer.apple.com for more info on how to write / use enums.