Search code examples
swiftanimationstoryboardxib

How to change view for label


I have a UILabel and I want to change its background view. Somebody advised me to use bezier but I want a simple variant.

My label:

it is my lable

What it should look like:

what should look like


Solution

  • Since these are not very complex shapes, I would suggest creating two white UIViews, rotating them 45 degrees and then adding them as subviews to the UILabel. The code would look something like this:

        myLabel.clipsToBounds = true
        // create the triangle on the left side of the label
        let leftSquare = UIView(frame: CGRect(x: myLabel.frame.height / -2, y: 0, width: myLabel.frame.height, height: myLabel.frame.height))
        leftSquare.translatesAutoresizingMaskIntoConstraints = true
        leftSquare.isUserInteractionEnabled = false
        leftSquare.backgroundColor = UIColor.white
        leftSquare.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 4)) // 45 degree rotation
        // create the triangle on the right side of the cell
        let rightSquare = UIView(frame: CGRect(x: myLabel.bounds.width - (myLabel.frame.height / 2), y: 0, width: myLabel.frame.height, height: myLabel.frame.height))
        rightSquare.translatesAutoresizingMaskIntoConstraints = true
        rightSquare.isUserInteractionEnabled = false
        rightSquare.backgroundColor = UIColor.white
        rightSquare.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 4))
        // add squares to label
        myLabel.addSubview(leftSquare)
        myLabel.addSubview(rightSquare)
        myLabel.sendSubview(toBack: leftSquare)
        myLabel.sendSubview(toBack: rightSquare)