Diogo Antunes
Diogo Antunes

Reputation: 2291

iOS Charts Marker View

I created a custom MarkerView from a .xib but it's always not centered in the proper set.

enter image description here

final class ChartMarkerView: MarkerView, ViewLoadable {

    @IBOutlet weak var laValue: UILabel!

    override required init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }

    func setUI() {

    }

    public override func refreshContent(entry: ChartDataEntry, highlight: Highlight) {
        laValue.text = String(entry.y)
        layoutIfNeeded()
    }
}

protocol ViewLoadable {
    var nibName: String { get }
}

extension ViewLoadable where Self: UIView {
    var containerView: UIView? { return subviews.first }

    var nibName: String { return String(describing: type(of: self)) }

    func loadViewFromXib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return view
    }

    func xibSetup() {
        let view = loadViewFromXib()
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleTopMargin]
        view.autoresizesSubviews = true
        backgroundColor = .clear
        addSubview(view)
    }
}

Upvotes: 0

Views: 3044

Answers (1)

Diogo Antunes
Diogo Antunes

Reputation: 2291

Turns out I just need to calculate the offset of the MarkerView and set it when loading the view:

offset.x = -self.frame.size.width / 2.0
offset.y = -self.frame.size.height - 7.0

Upvotes: 1

Related Questions