Luk*_*ong 135 ios swift uistackview
我试图UIStackView在Storyboard检查器中将背景从清除更改为白色,但在模拟时,堆栈视图的背景颜色仍然具有清晰的颜色.
如何更改背景颜色UIStackView?
Dha*_*esh 248
你不能这样做 -
UIStackView是一个非绘图视图,意味着drawRect()永远不会调用它,它的背景颜色会被忽略.如果您非常想要背景颜色,请考虑将堆栈视图放在另一个视图中UIView,并为该视图提供背景颜色.
来自HERE的参考资料.
Arb*_*tur 45
我是这样做的:
@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
}
}
Run Code Online (Sandbox Code Playgroud)
奇迹般有效
Mar*_*rný 29
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)
}
}
Run Code Online (Sandbox Code Playgroud)
也许最简单,更易读,更少hacky的方法是嵌入UIStackView到UIView视图中并将背景颜色设置为视图.
并且不要忘记在这两个视图之间正确配置自动布局约束... ;-)
Pitiphong是正确的,要获得带有背景颜色的stackview,请执行以下操作...
let bg = UIView(frame: stackView.bounds)
bg.autoresizingMask = [.flexibleWidth, .flexibleHeight]
bg.backgroundColor = UIColor.red
stackView.insertSubview(bg, at: 0)
Run Code Online (Sandbox Code Playgroud)
这将为您提供一个stackview,其内容将被放置在红色背景上.
要向stackview添加填充以使内容不与边缘齐平,请在代码中或故事板上添加以下内容...
stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
Run Code Online (Sandbox Code Playgroud)
值得指出的是,从iOS 14开始, UIStackViews 会渲染背景颜色。您可以使用 Background 属性从 Storyboard 设置 UIStackView 的背景。
或在代码中:
if #available(iOS 14.0, *) {
stackView.backgroundColor = .green
} else {
// Fallback for older versions of iOS
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46029 次 |
| 最近记录: |