Friday, 31 August 2018

Subviews of UIView misplaced when the parent view is in StackView

I want to create a button with a gradient border, everything works fine until I nest the GradientButton in a StackView. Then, I get this result for the last button in the horizontal StackView. Why is the subview becomes misplaced always for the last item?

enter image description here

Here is the GradientButton I created:

import Foundation
import UIKit

@IBDesignable class GradientButton: UIButton {

    @IBInspectable var startColor:  UIColor = UIColor.momaBackgroundGradient.begin
    @IBInspectable var endColor:    UIColor = UIColor.momaBackgroundGradient.end
    @IBInspectable var borderWidth: CGFloat = 2
    @IBInspectable var cornerRadius: CGFloat = 4

    override func awakeFromNib() {
        super.awakeFromNib()
        let gradientBorder = UIView(frame: self.frame)
        gradientBorder.configureGradient(withColors: [self.startColor, self.endColor], isHorizontal: true)
        gradientBorder.mask(withPath: UIBezierPath(roundedRect: self.frame.insetBy(dx: self.borderWidth, dy: self.borderWidth), cornerRadius: self.frame.height/2), inverse: true)
        gradientBorder.layer.cornerRadius = self.frame.height/2
        gradientBorder.layer.masksToBounds = true
        self.addSubview(gradientBorder)
    }
}



from Subviews of UIView misplaced when the parent view is in StackView

No comments:

Post a Comment