开发者

UILabel with subview

For some reasons I have to have a UILabel with a custom background view which I wanted to achieve by [label addSubview:backgroundView].

The background renders fine, but the Labels text does not appear.

What I can't d开发者_StackOverflowo is using the background color with a pattern image.


Try

[label insertSubview:backgroundView atIndex:0];

Edit:

I found something not sure how it would work tho. Try using the backgroundColor property. Something like:

label.backgroundColor = [UIColor colorWithPatternImage:yourImage];

Great, I was late with this again...


Really an old thread but I faced the same issue, and figured my solution might help someone (Using PureLayout and swift 4) and programmatically adding the views.

Sample usage in your 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
}()

Now you can just add this view and setup the constraints programmatically as you like.

For this implementation you need the UIView extension .wrapperOnTopOf which is implemented like:

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


As I've read some more posts I had to re-consider and in the end use a subclasses UIView. Not preferable as said in my post and comment, but finally working.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜