我想创建一个带有渐变边框的按钮,一切正常,直到将GradientButton
嵌套在StackView
中。然后,我得到水平StackView
中最后一个按钮的结果。为什么子视图总是总是放到最后一个项目上?
这是我创建的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)
}
}
答案 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
用于情节提要