Search code examples
iosswiftuislidersubview

custom UISlider subview frame is offset from main view


my custom uislider background uiview is offset from original view frame. and the further the the slider original (x,y) from 0,0 the more the offset.

Please check the image below.

uislider subview frame offset

import UIKit

class customSlier: UISlider {

    override func awakeFromNib() {
        super.awakeFromNib()

        self.initializeSomeSettings()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }     
    private func initializeSomeSettings() {            
        let view: UIView = UIView()
        view.frame = self.frame
        view.backgroundColor = UIColor.yellow
        self.insertSubview(view, belowSubview: self)
    }    
    override func layoutSubviews() {
        super.layoutSubviews()

    }

}


Solution

  • I think the problem is at this line:

    view.frame = self.frame
    

    Let's say your scroller is at position (10, 10). Then the background frame is also at position (10,10) in the coordinator of the scroll frame, which is (20,20) in the original view. My suggestion is to replace this line by this:

    view.frame = CGRect(origin: .zero, size: self.frame.size)
    

    Hope this helps.