Segmented Subview Control from Extension

I'm trying to add a subview below my UISegmentedControl from an extension, so when I add additional properties to this subtask, it can be reused from other UISegmentedControls in the application.

It appears in the right place, but for some reason it sometimes appears above some segments, and sometimes below. Did I miss something?

enter image description here

So far in my extension, what I have is:

import UIKit

extension UISegmentedControl {
    func addBackgroundView() {
        let backgroundView = UIView();
        backgroundView.frame = self.bounds;
        backgroundView.backgroundColor = UIColor.purple;
        self.insertSubview(backgroundView, belowSubview: self);
    }
}

      

And then I call the extensions function from the viewDidLoad method in the ViewController:

self.segmentedControlUnit.addBackgroundView();

      

+3


source to share


2 answers


I don't think you can do this. this is the UI Hierarchy when I select the 2nd segment enter image description here and this is the UI Hierarchy when I select the third segment



therefore the position of the segment changes depending on which segment you select. enter image description here

+1


source


Try to insert backgroundView

at index 0 to make sure it's under the entire subview



self.insertSubview(backgroundView, at: 0)

      

0


source







All Articles