Search code examples
iosswiftuilabelframecgrect

Why my UILabel doesn't conforms to the inital frame?


I'm trying to create a popup label over the imageview. But in my application it doesn't work. I've made a test application with the same screen: UIImageView and below a UIView with a UIButton on the view.

So, where are two questions.

  1. What could be difference in a code for such a different behaviour?
  2. Why in my application the UILabel doesn't conforms to the initial frame?

The code of the function inside my viewController is the same:

private func showBanner(startY: CGFloat, targetView: UIView) {
    let height: CGFloat = 42
    let finishY = startY - height
    
    let bannerLabel = UILabel(frame: CGRect(x: 0, y: startY, width: self.view.frame.width, height: height))
    bannerLabel.translatesAutoresizingMaskIntoConstraints = false
    bannerLabel.font = UIFont.systemFont(ofSize: 13, weight: .regular)
    bannerLabel.textColor = .lightGray
    bannerLabel.backgroundColor = .black
    bannerLabel.textAlignment = .center
    bannerLabel.numberOfLines = 1
    bannerLabel.text = "You've added the item to the favorites"
    
    targetView.addSubview(bannerLabel)
    
    UIView.animate(withDuration: 0.5, animations: {
        bannerLabel.frame = CGRect(x: 0,
                                   y: finishY,
                                   width: self.view.frame.width,
                                   height: height
                                    )
    }) {
        _ in

        UIView.animate(withDuration: 0.5, delay: 1.0, options: .curveLinear, animations: {
            bannerLabel.frame = CGRect(x: 0,
                                       y: startY,
                                       width: self.view.frame.width,
                                       height: height
                                        )
        }, completion: {
            _ in
            bannerLabel.removeFromSuperview()
        })
    }
}

The function is being called so:

showBanner(startY: itemsImageView.frame.maxY, targetView: itemsImageView)

This is how it should be and is in the test app

This is my application and how it should NOT be


Solution

  • The problem was in the line: bannerLabel.translatesAutoresizingMaskIntoConstraints = false

    As soon as this line was removed, the problem has dissapeared.