当父视图位于StackView中时,UIView的子视图放错了位置

时间:2018-08-28 03:36:42

标签: ios swift

我想创建一个带有渐变边框的按钮,一切正常,直到将GradientButton嵌套在StackView中。然后,我得到水平StackView中最后一个按钮的结果。为什么子视图总是总是放到最后一个项目上?

enter image description here

这是我创建的GradientButton:

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)
    }
}

2 个答案:

答案 0 :(得分:2)

您的渐变视图在初始化时使用其父级的frame。像这样将其更改为bounds

let gradientBorder = UIView(frame: self.bounds)

答案 1 :(得分:0)

/Text Label
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.yellow
textLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text  = "Hi World"
textLabel.textAlignment = .center

//Stack View
let stackView   = UIStackView()
stackView.axis  = UILayoutConstraintAxis.horizontal
stackView.distribution  = UIStackViewDistribution.equalSpacing
stackView.alignment = UIStackViewAlignment.center
stackView.spacing   = 16.0

stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(textLabel)
stackView.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(stackView)

//Constraints
stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

用于情节提要

enter image description here