首页 文章

如何更改UIStackView的背景颜色?

提问于
浏览
93

我试图在Storyboard检查器中将 UIStackView 背景从清除更改为白色,但在模拟时,堆栈视图的背景颜色仍然具有清晰的颜色 .
如何更改 UIStackView 的背景颜色?

14 回答

  • 0
    UIStackView *stackView;
    UIView *stackBkg = [[UIView alloc] initWithFrame:CGRectZero];
    stackBkg.backgroundColor = [UIColor redColor];
    [self.view insertSubview:stackBkg belowSubview:stackView];
    stackBkg.translatesAutoresizingMaskIntoConstraints = NO;
    [[stackBkg.topAnchor constraintEqualToAnchor:stackView.topAnchor] setActive:YES];
    [[stackBkg.bottomAnchor constraintEqualToAnchor:stackView.bottomAnchor] setActive:YES];
    [[stackBkg.leftAnchor constraintEqualToAnchor:stackView.leftAnchor] setActive:YES];
    [[stackBkg.rightAnchor constraintEqualToAnchor:stackView.rightAnchor] setActive:YES];
    
  • 20

    你不能这样做 - UIStackView是一个非绘图视图,这意味着永远不会调用drawRect()并忽略它的背景颜色 . 如果您非常想要背景颜色,请考虑将堆栈视图放在另一个UIView中,并为该视图提供背景颜色 .

    参考来自HERE .

  • -2

    UIStackView 是一个非渲染元素,因此,它不会在屏幕上绘制 . 这意味着改变 backgroundColor 基本上什么都不做 . 如果要更改背景颜色,只需将 UIView 添加为子视图(未排列),如下所示:

    extension UIStackView {
    
        func addBackground(color: UIColor) {
            let subview = UIView(frame: bounds)
            subview.backgroundColor = color
            subview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            insertSubview(subview, at: 0)
        }
    
    }
    
  • 2

    以下是添加堆栈视图背景颜色的简要概述 .

    class RevealViewController: UIViewController {
    
        @IBOutlet private weak var rootStackView: UIStackView!
    

    创建带圆角的背景视图

    private lazy var backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = .purple
        view.layer.cornerRadius = 10.0
        return view
    }()
    

    为了使它显示为背景,我们将它添加到索引0处的根堆栈视图的子视图数组中 . 这将它放在堆栈视图的排列视图后面 .

    private func pinBackground(_ view: UIView, to stackView: UIStackView) {
        view.translatesAutoresizingMaskIntoConstraints = false
        stackView.insertSubview(view, at: 0)
        view.pin(to: stackView)
    }
    

    通过在UIView上使用小扩展,添加约束以将backgroundView固定到堆栈视图的边缘 .

    public extension UIView {
      public func pin(to view: UIView) {
        NSLayoutConstraint.activate([
          leadingAnchor.constraint(equalTo: view.leadingAnchor),
          trailingAnchor.constraint(equalTo: view.trailingAnchor),
          topAnchor.constraint(equalTo: view.topAnchor),
          bottomAnchor.constraint(equalTo: view.bottomAnchor)
          ])
      }
    }
    

    viewDidLoad 调用 pinBackground

    override func viewDidLoad() {
      super.viewDidLoad()
      pinBackground(backgroundView, to: rootStackView)
    }
    

    参考来自:HERE

  • 2

    Xamarin,C#版本:

    var stackView = new UIStackView { Axis = UILayoutConstraintAxis.Vertical };
    
    UIView bg = new UIView(stackView.Bounds);
    bg.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
    bg.BackgroundColor = UIColor.White;
    stackView.AddSubview(bg);
    
  • 0

    你可以这样做:

    stackView.backgroundColor = UIColor.blue
    

    通过提供覆盖 backgroundColor 的扩展名:

    extension UIStackView {
    
        override open var backgroundColor: UIColor? {
    
            get {
                return super.backgroundColor
            }
    
            set {
    
                super.backgroundColor = newValue
    
                let tag = -9999
                for view in subviews where view.tag == tag {
                    view.removeFromSuperview()
                }
    
                let subView = UIView()
                subView.tag = tag
                subView.backgroundColor = newValue
                subView.translatesAutoresizingMaskIntoConstraints = false
                self.addSubview(subView)
                subView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
                subView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
                subView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
                subView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
            }
    
        }
    
    }
    
  • 7

    也许最容易,更可读和更少hacky的方法是将 UIStackView 嵌入 UIView 并将背景颜色设置为视图 .

    并且不要忘记在这两个视图之间正确配置自动布局约束... ;-)

  • 188

    这适用于Swift 3和iOS 10:

    let stackView = UIStackView()
    let subView = UIView()
    subView.backgroundColor = .red
    subView.translatesAutoresizingMaskIntoConstraints = false
    stackView.addSubview(subView) // Important: addSubview() not addArrangedSubview()
    
    // use whatever constraint method you like to 
    // constrain subView to the size of stackView.
    subView.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true
    subView.bottomAnchor.constraint(equalTo: stackView.bottomAnchor).isActive = true
    subView.leftAnchor.constraint(equalTo: stackView.leftAnchor).isActive = true
    subView.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
    
    // now add your arranged subViews...
    stackView.addArrangedSubview(button1)
    stackView.addArrangedSubview(button2)
    
  • 3

    在iOS10中,@ Arbitur的答案在设置颜色后需要setNeedsLayout . 这是需要的改变:

    override var backgroundColor: UIColor? {
        get { return color }
        set { 
            color = newValue
            setNeedsLayout()
        }
    }
    
  • 5

    TL; DR:执行此操作的官方方法是使用 addSubview: 方法将空视图添加到堆栈视图中,并设置添加的视图背景 .

    解释:UIStackView是一个特殊的UIView子类,只做布局而不是绘图 . 它的许多属性都不会像往常那样起作用 . 并且由于UIStackView将仅布置其排列的子视图,这意味着您可以简单地使用 addSubview: 方法添加UIView,设置其约束和背景颜色 . 这是实现你想要的官方方式quoted from WWDC session

  • 40

    Pitiphong是正确的,要获得带有背景颜色的stackview,请执行以下操作...

    let bg = UIView(frame: stackView.bounds)
      bg.autoresizingMask = [.flexibleWidth, .flexibleHeight]
      bg.backgroundColor = UIColor.red
    
      stackView.addSubview(bg)
    

    这将为您提供一个堆栈视图,其内容将放置在红色背景上 .

    要向stackview添加填充以使内容不与边缘齐平,请在代码中或故事板上添加以下内容...

    stackView.isLayoutMarginsRelativeArrangement = true
      stackView.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
    
  • 0

    您可以向StackView插入一个子图层,它适用于我:

    @interface StackView ()
    @property (nonatomic, strong, nonnull) CALayer *ly;
    @end
    
    @implementation StackView
    
    - (instancetype)initWithFrame:(CGRect)frame {
        self = [super initWithFrame:frame];
        if (self) {
            _ly = [CALayer new];
            [self.layer addSublayer:_ly];
        }
        return self;
    }
    
    - (void)setBackgroundColor:(UIColor *)backgroundColor {
        [super setBackgroundColor:backgroundColor];
        self.ly.backgroundColor = backgroundColor.CGColor;
    }
    
    - (void)layoutSubviews {
        self.ly.frame = self.bounds;
        [super layoutSubviews];
    }
    
    @end
    
  • 8

    我是这样做的:

    @IBDesignable
    class StackView: UIStackView {
       @IBInspectable private var color: UIColor?
        override var backgroundColor: UIColor? {
            get { return color }
            set {
                color = newValue
                self.setNeedsLayout() // EDIT 2017-02-03 thank you @BruceLiu
            }
        }
    
        private lazy var backgroundLayer: CAShapeLayer = {
            let layer = CAShapeLayer()
            self.layer.insertSublayer(layer, at: 0)
            return layer
        }()
        override func layoutSubviews() {
            super.layoutSubviews()
            backgroundLayer.path = UIBezierPath(rect: self.bounds).cgPath
            backgroundLayer.fillColor = self.backgroundColor?.cgColor
        }
    }
    

    奇迹般有效

  • 0

    子类UIStackView

    class CustomStackView : UIStackView {
    
    private var _bkgColor: UIColor?
    override public var backgroundColor: UIColor? {
        get { return _bkgColor }
        set {
            _bkgColor = newValue
            setNeedsLayout()
        }
    }
    
    private lazy var backgroundLayer: CAShapeLayer = {
        let layer = CAShapeLayer()
        self.layer.insertSublayer(layer, at: 0)
        return layer
    }()
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        backgroundLayer.path = UIBezierPath(rect: self.bounds).cgPath
        backgroundLayer.fillColor = self.backgroundColor?.cgColor
    }
    }
    

    然后在你的班上

    yourStackView.backgroundColor = UIColor.lightGray
    

相关问题