Walker
Walker

Reputation: 1147

swift - change color of top UIToolbar border

I'm trying to change the color of the top border on a UIToolbar.

I tried:

layer.borderWidth = 1
layer.borderColor = UIColor(r: 250, g: 250, b: 250).CGColor

That didn't work.

Suggestions? Thank you

Upvotes: 2

Views: 2600

Answers (6)

Krizai
Krizai

Reputation: 610

That's actually a shadow image, so just create some 1 pixel image with necessary color and use

[toolbar setShadowImage:<your image> forToolbarPosition:UIBarPositionAny];

Upvotes: 0

Stefan
Stefan

Reputation: 300

You can use:

- (void)setToolbarLineWith:(UIColor *)color
{
    for(UIView *v in self.navigationController.toolbar.subviews){
        if([NSStringFromClass([v class]) isEqualToString:@"_UIBarBackground"])
        {
            for(UIView *w in v.subviews){
                if([NSStringFromClass([w class]) isEqualToString:@"UIImageView"])
                {
                    [w setBackgroundColor:color];
                }
            }
        }
    }
}

and run with:

[self setToolbarLineWith:[UIColor redColor]];

Upvotes: 1

Wilson
Wilson

Reputation: 9136

I've done it using this code:

class ViewController: UIViewController {
  
  @IBOutlet weak var toolBar: UIToolbar!
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    // the layer with the width of the device
    // and height of 0.5 px
    let topBorder = CALayer()
    topBorder.frame = CGRectMake(0, 0, view.frame.size.width, 0.5)
    topBorder.backgroundColor = UIColor.redColor().CGColor
    
    // adding the layer to the top
    // of the toolBar
    toolBar.layer.addSublayer(topBorder)
  }
}

Result:

enter image description here

Source: https://blog.adamcooke.io/set-the-top-border-colour-of-a-uinavbar-d9035c6b4fdb#.f37molpsj

Upvotes: 5

pedrouan
pedrouan

Reputation: 12910

If you don't like its color, and as it isn't possible to change it, fastest hack is to get rid of that hairline - It is not actually a border, it's a shadow.

toolbar.clipsToBounds = true

OR:

toolbar.layer.shadowOpacity = 0

Or maybe you are able to change its shadow image:

UITabbar.appearance().shadowImage = UIImage.colorForNavBar(.red)

Upvotes: 1

Tal Zion
Tal Zion

Reputation: 6526

You need to set RGB colours divided by 255.0 to get a 0 to 1 colour.

For example:

layer.borderWidth = 1
layer.borderColor = UIColor(r: 250/255, g: 250/255, b: 250/255).CGColor

Upvotes: 0

user3734410
user3734410

Reputation: 13

UIColor works between 0 and 1 so for example:

If you want 250 as your red value you need to do 250/255. I had this same problem and found that just by adding the /255 after the value the color works as expected.

The /255 creates the value in the proper range. You could also do the division and put in the decimal approximation.

If you need any more help or clarification please let me know.

Upvotes: 0

Related Questions