2

いくつかの理由で、[label addSubview:backgroundView]によって実現したいカスタム背景ビューを備えたUILabelが必要です。

背景は正常にレンダリングされますが、ラベルテキストは表示されません。

私ができないのは、パターン画像で背景色を使用することです。

4

3 に答える 3

1

試す

[label insertSubview:backgroundView atIndex:0];

編集:

私はそれがどのように機能するかわからない何かを見つけました。backgroundColorプロパティを使用してみてください。何かのようなもの:

label.backgroundColor = [UIColor colorWithPatternImage:yourImage];

素晴らしい、私はこれに再び遅れました...

于 2011-07-07T08:53:43.970 に答える
1

本当に古いスレッドですが、私は同じ問題に直面し、私の解決策が誰かを助け(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
   }
}
于 2021-08-22T08:51:07.757 に答える
0

さらにいくつかの投稿を読んだので、再考する必要があり、最終的にはサブクラスUIViewを使用しました。私の投稿とコメントで述べたように好ましくありませんが、最終的には機能しています。

于 2011-07-29T12:58:56.687 に答える