我试图在Storyboard检查器中将UIStackView
背景从clear更改为white,但在模拟时,堆栈视图的背景颜色仍然具有清晰的颜色。
如何更改UIStackView
的背景颜色?
答案 0 :(得分:222)
你不能这样做 -
UIStackView
是非绘画视图,意思是 永远不会调用drawRect()
,并忽略其背景颜色。如果你 拼命想要背景颜色,考虑放置堆栈视图 在另一个UIView
内,并为该视图提供背景颜色。
来自HERE的参考。
修改强>
您可以按照HERE向UIStackView
添加子视图。并为其指定颜色。请查看以下extension
:
extension UIStackView {
func addBackground(color: UIColor) {
let subView = UIView(frame: bounds)
subView.backgroundColor = color
subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(subView, at: 0)
}
}
您可以像以下一样使用它:
stackView.addBackground(color: .red)
答案 1 :(得分:42)
我这样做:
@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
}
}
像魅力一样工作
答案 2 :(得分:27)
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)
}
}
答案 3 :(得分:8)
TL; DR:执行此操作的官方方法是使用addSubview:
方法将空视图添加到堆栈视图中,然后设置添加的视图背景。
解释:UIStackView是一个特殊的UIView子类,只做布局而不是绘图。因此,它的许多房产都像往常一样无法正常工作。由于UIStackView将仅布置其排列的子视图,这意味着您只需使用addSubview:
方法添加UIView,设置其约束和背景颜色即可。这是实现您想要的quoted from WWDC session
答案 4 :(得分:7)
将UIStackView
嵌入到UIView
中并将背景颜色设置为视图时,最简单,更易读,更少hacky的方法可能是最简单的。
并且不要忘记在这两个视图之间正确配置自动布局约束...... ;-)
答案 5 :(得分:7)
Pitiphong是正确的,要获得具有背景颜色的stackview,请执行以下操作...
let bg = UIView(frame: stackView.bounds)
bg.autoresizingMask = [.flexibleWidth, .flexibleHeight]
bg.backgroundColor = UIColor.red
stackView.insertSubview(bg, at: 0)
这将为您提供一个堆栈视图,其内容将放置在红色背景上。
要向stackview添加填充以使内容不与边缘齐平,请在代码中或故事板上添加以下内容...
stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
答案 6 :(得分:4)
值得指出的是,从 iOS 14 开始,UIStackViews会渲染背景颜色。您可以通过Storyboard的Background属性设置UIStackView的背景。
或使用以下代码:
if #available(iOS 14.0, *) {
stackView.backgroundColor = .green
} else {
// Fallback for older versions of iOS
}
答案 7 :(得分:3)
在iOS10中,@ Arbitur的答案在设置颜色后需要setNeedsLayout。这是需要的改变:
override var backgroundColor: UIColor? {
get { return color }
set {
color = newValue
setNeedsLayout()
}
}
答案 8 :(得分:2)
这适用于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)
答案 9 :(得分: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)
])
}
}
从pinBackground
viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
pinBackground(backgroundView, to: rootStackView)
}
参考文献:HERE
答案 10 :(得分:2)
您可以扩展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)
])
}
}
用法:
yourStackView.setBackgroundColor(.black)
答案 11 :(得分:0)
有很好的答案,但我发现它们不完整,所以这是我基于其中最好的版本:
/// This extension addes missing background color to stack views on iOS 13 and earlier
extension UIStackView {
private struct CustomAttributeNames {
static var _backgroundView = "_backgroundView"
}
@IBInspectable var customBackgroundColor: UIColor? {
get { backgroundColor }
set { setBackgroundColor(newValue) }
}
var backgroundView: UIView {
if let view = objc_getAssociatedObject(self, &CustomAttributeNames._backgroundView) as? UIView {
return view
}
let view = UIView(frame: bounds)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(view, at: 0)
objc_setAssociatedObject(self,
&CustomAttributeNames._backgroundView,
view,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return view
}
func setBackgroundColor(_ color: UIColor?) {
backgroundColor = color
backgroundView.backgroundColor = color
}
}
答案 12 :(得分:0)
如果您想通过设计器本身进行控制,请将此扩展添加到堆栈视图中
@IBInspectable var customBackgroundColor: UIColor?{
get{
return backgroundColor
}
set{
backgroundColor = newValue
let subview = UIView(frame: bounds)
subview.backgroundColor = newValue
subview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(subview, at: 0)
}
}
答案 13 :(得分:0)
我们可以有一个自定义类StackView
,如下所示:
class StackView: UIStackView {
lazy var backgroundView: UIView = {
let otherView = UIView()
addPinedSubview(otherView)
return otherView
}()
}
extension UIView {
func addPinedSubview(_ otherView: UIView) {
addSubview(otherView)
otherView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
otherView.trailingAnchor.constraint(equalTo: trailingAnchor),
otherView.topAnchor.constraint(equalTo: topAnchor),
otherView.heightAnchor.constraint(equalTo: heightAnchor),
otherView.widthAnchor.constraint(equalTo: widthAnchor),
])
}
}
它可以像这样使用:
let stackView = StackView()
stackView.backgroundView.backgroundColor = UIColor.lightGray
这比其他人建议的添加扩展功能func addBackground(color: UIColor)
稍好。背景视图是惰性的,因此只有您实际调用stackView.backgroundView.backgroundColor = ...
时才能创建背景视图。并且多次设置/更改背景颜色不会导致在堆栈视图中插入多个子视图。
答案 14 :(得分:0)
您不能将背景添加到stackview。 但是您可以做的是在视图中添加stackview,然后设置视图背景,这将完成工作。 *它不会中断stackview的流程。 希望这会有所帮助。
答案 15 :(得分:0)
对于Subclassing UI组件,我有点怀疑。这就是我的使用方式,
struct CustomAttributeNames{
static var _backgroundView = "_backgroundView"
}
extension UIStackView{
var backgroundView:UIView {
get {
if let view = objc_getAssociatedObject(self, &CustomAttributeNames._backgroundView) as? UIView {
return view
}
//Create and add
let view = UIView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
insertSubview(view, at: 0)
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: self.topAnchor),
view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
view.bottomAnchor.constraint(equalTo: self.bottomAnchor),
view.trailingAnchor.constraint(equalTo: self.trailingAnchor)
])
objc_setAssociatedObject(self,
&CustomAttributeNames._backgroundView,
view,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return view
}
}
}
这是用法
stackView.backgroundView.backgroundColor = .white
stackView.backgroundView.layer.borderWidth = 2.0
stackView.backgroundView.layer.borderColor = UIColor.red.cgColor
stackView.backgroundView.layer.cornerRadius = 4.0
注意:使用这种方法,如果要设置边框,则必须在stackView上设置layoutMargins
,以便边框可见。
答案 16 :(得分: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
答案 17 :(得分: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
答案 18 :(得分:0)
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);
答案 19 :(得分: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 :(得分:-1)
尝试BoxView。它类似于UIStackView,但是它正在呈现并支持更多的布局选项。
答案 21 :(得分:-1)
你可以这样做:
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
}
}
}