由于某些原因,我必须有一个带有自定义背景视图的 UILabel,我想通过 [label addSubview:backgroundView] 来实现。
背景渲染得很好,但标签文本没有出现。
我不能做的是使用带有图案图像的背景颜色。
由于某些原因,我必须有一个带有自定义背景视图的 UILabel,我想通过 [label addSubview:backgroundView] 来实现。
背景渲染得很好,但标签文本没有出现。
我不能做的是使用带有图案图像的背景颜色。
尝试
[label insertSubview:backgroundView atIndex:0];
编辑:
我发现了一些不确定它会如何工作的东西。尝试使用 backgroundColor 属性。就像是:
label.backgroundColor = [UIColor colorWithPatternImage:yourImage];
太好了,我又迟到了……
确实是一个旧线程,但我遇到了同样的问题,并且认为我的解决方案可能会帮助某人(使用 PureLayout 和 swift 4)并以编程方式添加视图。
viewController 中的示例用法:
private lazy var labelContainer: UIView = {
// Configure the label:
let labelView = UILabel.newAutoLayout()
labelView.text = label
labelView.textColor = .red
labelView.textAlignment = .center
labelView.numberOfLines = 1
// Configure your custom background view (UIView for this sample)
let bgView = UIView.newAutoLayout()
bgView.backgroundColor = .blue
// The combined view with "padding":
let paddingVertical = 12
let paddingHorizontal = 16
let padding = UIEdgeInsets.init(top: paddingVertical, left: paddingHorizontal, bottom: paddingVertical, right: paddingHorizontal)
let view = labelView.wrapperOnTopOf(bgView: bgView, insets: padding)
view.layer.cornerRadius = 15
view.layer.masksToBounds = true
return view
}()
现在您可以添加此视图并根据需要以编程方式设置约束。
对于此实现,您需要 UIView 扩展 .wrapperOnTopOf ,其实现如下:
extension UIView {
/**
* Function to wrap the current view in a UIView on top of another view
* - UIView
*/
func wrapperOnTopOf(bgView: UIView, insets: UIEdgeInsets = UIEdgeInsets.zero) -> UIView {
let container = UIView.newAutoLayout()
bgView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
container.insertSubview(bgView, at: 0)
container.insertSubview(self, at: 1)
// Let this view determine the size of the container:
self.autoPinEdgesToSuperviewEdges(with: insets)
return container
}
}
当我阅读更多帖子时,我不得不重新考虑并最终使用 UIView 的子类。不像我的帖子和评论中所说的那样可取,但最终起作用了。