ios 如何更改 UIStackView 的背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34868344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:35:56  来源:igfitidea点击:

How to change the background color of UIStackView?

iosswiftuistackview

提问by LukasTong

I tried to change the UIStackViewbackground from clear to white in Storyboard inspector, but when simulating, the background color of the stack view still has a clear color.
How can I change the background color of a UIStackView?

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

回答by Dharmesh Kheni

You can't do this – UIStackViewis a non-drawing view, meaning that drawRect()is never called and its background color is ignored. If you desperately want a background color, consider placing the stack view inside another UIViewand giving that view a background color.

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

Reference from HERE.

这里参考。

EDIT:

编辑:

You can add a subView to UIStackViewas mentioned HEREor in this answer (below)and assign a color to it. Check out below extensionfor that:

您可以将子视图添加到此处或在此答案(如下)中UIStackView提到的,并为其分配颜色。请查看以下内容:extension

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

And you can use it like:

你可以像这样使用它:

stackView.addBackground(color: .red)

回答by Arbitur

I do it like this:

我这样做:

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

Works like a charm

奇迹般有效

回答by Marián ?erny

UIStackViewis a non-rendering element, and as such, it does not get drawn on the screen. This means that changing backgroundColoressentially does nothing. If you want to change the background color, just add a UIViewto it as a subview (that is not arranged) like below:

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

}

回答by MonsieurDart

Maybe the easiest, more readable and less hacky way would be to embed the UIStackViewinto a UIViewand set the background color to the view.

也许最简单、更易读且不那么笨拙的方法是将 嵌入UIStackView到 a 中UIView并将背景颜色设置为视图。

And don't forget to configure properly the Auto Layout constraints between those two views… ;-)

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

回答by Michael Long

Pitiphong is correct, to get a stackview with a background color do something like the following...

Pitiphong 是正确的,要获得具有背景颜色的堆栈视图,请执行以下操作...

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

  stackView.insertSubview(bg, at: 0)

This will give you a stackview whose contents will be placed on a red background.

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

To add padding to the stackview so the contents aren't flush with the edges, add the following in code or on the storyboard...

要将填充添加到堆栈视图以使内容不与边缘齐平,请在代码或故事板上添加以下内容...

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

回答by Pitiphong Phongpattranont

TL;DR: The official way to do this is by adding an empty view into stack view using addSubview:method and set the added view background instead.

TL;DR:官方的方法是使用addSubview:方法将空视图添加到堆栈视图中,并改为设置添加的视图背景。

The explanation: UIStackView is a special UIView subclass that only do the layout not drawing. So many of its properties won't work as usual. And since UIStackView will layout its arranged subviews only, this mean that you can simply add it a UIView with addSubview:method, set its constraints and background color. This is the official way to achieve what you want quoted from WWDC session

解释: UIStackView 是一个特殊的 UIView 子类,只做布局不绘制。它的许多属性将无法像往常一样工作。而且由于 UIStackView 将仅布局其排列的子视图,这意味着您可以简单地将它添加到 UIViewaddSubview:方法,设置其约束和背景颜色。这是实现您想要从 WWDC 会话中引用的内容的官方方法

回答by BruceLiu

In iOS10, @Arbitur's answer needs a setNeedsLayout after color is set. This is the change which is needed:

在 iOS10 中,@Arbitur 的答案在设置颜色后需要一个 setNeedsLayout。这是所需的更改:

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

回答by Murray Sagal

This works for me in Swift 3 and iOS 10:

这在 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)

回答by Nhon Nguyen

You could make a small extension of UIStackView

你可以做一个小的扩展 UIStackView

extension UIStackView {
    func setBackgroundColor(_ color: UIColor) {
        let backgroundView = UIView(frame: .zero)
        backgroundView.backgroundColor = color
        backgroundView.translatesAutoresizingMaskIntoConstraints = false
        self.insertSubview(backgroundView, at: 0)
        NSLayoutConstraint.activate([
            backgroundView.topAnchor.constraint(equalTo: self.topAnchor),
            backgroundView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            backgroundView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            backgroundView.trailingAnchor.constraint(equalTo: self.trailingAnchor)
            ])
    }
}

Usage:

用法:

yourStackView.setBackgroundColor(.black)

回答by kurrodu

Here is a brief overview for adding a Stack view Background Color.

这是添加堆栈视图背景颜色的简要概述。

class RevealViewController: UIViewController {

    @IBOutlet private weak var rootStackView: UIStackView!

Creating background view with rounded corners

创建带圆角的背景视图

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

To make it appear as the background we add it to the subviews array of the root stack view at index 0. That puts it behind the arranged views of the stack view.

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

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

Add constraints to pin the backgroundView to the edges of the stack view, by using a small extension on UIView.

通过在 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)
      ])
  }
}

call the pinBackgroundfrom viewDidLoad

呼叫pinBackground来自viewDidLoad

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

Reference from: HERE

参考资料:这里