Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift iOS UITabBar Customization

I have a tab bar. I changed its colour, gave it a corner radius, set its border width and colour, and everything is working good. Until now, everything is done in a storyboard.

Now I want to give it left and right margins, as by default it is sticking to the screen's edges.

This is the tab bar's current look:

enter image description here

The black arrows point to the lines that stick to the screen's edges. I want space between this line and the edges.

like image 268
Hafiz Shoaib Awan Avatar asked Oct 30 '18 06:10

Hafiz Shoaib Awan


1 Answers

You can create this placeholder view inside a custom UITabBar as below,

class CustomTabBar: UITabBar {

    let roundedView = UIView(frame: .zero)

    override func awakeFromNib() {
        super.awakeFromNib()

        roundedView.layer.masksToBounds = true
        roundedView.layer.cornerRadius = 12.0
        roundedView.layer.borderWidth = 2.0
        roundedView.isUserInteractionEnabled = false
        roundedView.layer.borderColor = UIColor.black.cgColor
        self.addSubview(roundedView)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let margin: CGFloat = 12.0
        let position = CGPoint(x: margin, y: 0)
        let size = CGSize(width: self.frame.width - margin * 2, height: self.frame.height)
        roundedView.frame = CGRect(origin: position, size: size)
    }
}

Set this class for TabBar in storyboard/xib. It should give you the following,

enter image description here

like image 65
Kamran Avatar answered Oct 21 '22 16:10

Kamran