简体   繁体   中英

How to get frame of a view and set it to gradient's frame

all I have a page control with some specified anchors as below. I want to apply a gradient to its background. But I am unable to get the page control's actual frame. Can anybody help me.

this is the page control's frame which is working fine.

pageControl.setAnchor(top: nil, bottom: buttonsContainerView.topAnchor, left: view.leftAnchor, right: view.rightAnchor);
        pageControl.heightAnchor.constraint(equalToConstant: 30).isActive = true;

Calling function to apply the gradient to the page control.

addGradientForPageControl(view: pageControl);

The page control code

lazy var pageControl: UIPageControl = {
        let pc = UIPageControl();
        pc.pageIndicatorTintColor = UIColor.black;
        pc.currentPageIndicatorTintColor = UIColor.white;
        pc.numberOfPages = self.pages.count;
        pc.translatesAutoresizingMaskIntoConstraints = false;
        pc.addTarget(self, action: #selector(handlePageClick), for: .touchUpInside);
        return pc;
    }();

Gradient function.

func addGradientForPageControl(view: UIView){
        let gradient: CAGradientLayer = CAGradientLayer();
        gradient.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height);
        print(Int(view.layer.borderWidth));
        let topColor = UIColor(red: 107/255, green: 143/255, blue: 133/255, alpha: 1).cgColor;
        let bottomColor = UIColor(red: 68/255, green: 126/255, blue: 114/255, alpha: 1).cgColor;
        gradient.colors = [topColor, bottomColor];
        view.layer.addSublayer(gradient);
    }

if I call the above function, I always get the gradient's frame to be (0,0,0,0). This causes no gradient on the background. Is there any way to get the frame of the page control by calling like view.widthAnchor.something to get the frame width and height.

You are probably adding gradient before the view is assigned a frame and laid out on the screen. Try adding the gradient in viewDidLayoutSubviews() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM