frame.size.height 및 width 가 0일 때

🌎·2023년 6월 23일
0

header.insertSubview(card, at: 0)
card.leadingAnchor.constraint(equalTo: header.leadingAnchor, constant: 20.0).isActive = true
card.trailingAnchor.constraint(equalTo: header.trailingAnchor, constant: -20.0).isActive = true
card.heightAnchor.constraint(equalToConstant: 213.0).isActive = true
card.topAnchor.constraint(equalTo: header.topAnchor, constant: 15.0).isActive = true
// card.layoutIfNeeded()
card.setGradient(color1: UIColor.black, color2: UIColor.blue)
            
extension UIView {
    
    func setGradient(color1: UIColor, color2: UIColor) {
        
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame.size = CGSize(width: 300, height: 300)
        gradient.colors = [color1.cgColor, color2.cgColor]
//        gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
//        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
        print(self.bounds.size.height)
        gradient.frame = bounds
        layer.masksToBounds = true
        layer.insertSublayer(gradient, at: 0)
//        layer.addSublayer(gradient)
    }

}

위처럼 header 라는 UIView 안에 card 라는 UIView 를 넣고, setGradient() 라는 함수를 만들어서 gradient를 주려고 했는데, 아무리 해도 안먹히더라...

대체 왜그럴까 하고, card.layout.size.height 랑 card.layout.size.width를 출력해보니 둘 다 0, 0 이 나왔다...

검색을 해보니 card.layoutIfNeeded() 를 추가해주니 잘 되었다. (주석처리 되어 있는 것)

그런데 layoutIfNeeded() 를 사용하는 것을 피하라는 말이 있어서, frame에 대해서 조금 더 공부를 했다.

https://babbab2.tistory.com/44 (공부한 사이트)

하지만 대체 왜 size 의 모든 값들이 0이 나오는지 모르겠어서, 찾아보니

When you set up your views in viewDidLoad() the actual sizes have not yet been calculated. Try measuring the width in viewDidAppear(). By that time everything should be set up.

viewDidLoad() 일 때는 아직 실제 사이즈가 계산되어지지 않고, viewDidAppear() 일 때 측정하면 값이 나온다고 한다. 아마 UITableViewDelegate의 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? 같은 경우도 아직 viewDidAppear()가 호출된 상태가 아니기 때문에, 즉 뷰에 띄워진 상태가 아니기 때문에 무수한 0을 뱉어낸 것 같다.

그래서 혹여나! 싶어서 viewDidLoad() 에다가 setGradient()를 다시 호출해보았다.

    override func viewDidAppear(_ animated: Bool) {
    
        super.viewDidAppear(animated)
        
        card.setGradient(color1: UIColor.black, color2: UIColor.blue)
        
    }


완전잘됨...!!

UIViewController의 LifeCycle을 찾아보고 한 번 테스트 해봤다.

(213.0 이라고 출력된 것은 무시해도 된다.)
viewDidAppear() 이전까지 frame.size 출력 값이 다 (0.0, 0.0)인 것을 확인할 수 있었다! 그리고 viewDidAppear() 이전에 tableView와 관련된 함수가 호출되는 것까지 확인했다. 그러다보니 frame값이 0이 나온 것 같다.

역시 사람은 서칭을 해야해...b

profile
영차영차

0개의 댓글