Search code examples
iosswiftuiscrollviewuibutton

Trying to change UIButton title color and frame on scrollview scroll


I am trying to change the title color of a UIButton as well as the frame of the button when I scroll a scrollview to the last page. The UIButton is outside of the scrollview.

If I only change the frame it works, and if I only change the title color it works, but when I try to change both the frame doesn't change.

The button I am trying to change is signupButton

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageNum = Int(scrollView.contentOffset.x / scrollView.frame.size.width)

    if(pageNum == 2) {
        UIView.animate(withDuration: 0.3) {
            self.nextButton.layer.opacity = 0.0
            self.signupButton.backgroundColor = UIColor(red: 75/255, green: 159/255, blue: 186/255, alpha: 1.0)
            self.signupButton.frame.size = CGSize(width: UIScreen.main.bounds.width - 69,height: 45)
            self.signupButton.setTitleColor(.white, for: .normal)
        }

    } else {
        UIView.animate(withDuration: 0.3) {
            self.nextButton.layer.opacity = 1.0
            self.signupButton.backgroundColor = .clear
            self.signupButton.setTitleColor(UIColor(red: 75/255, green: 159/255, blue: 186/255, alpha: 1.0), for: .normal)
        }
    }

    UIView.animate(withDuration: 0.2) {
        self.pageControl.currentPage = pageNum
    }
}

I expected both the title color and the frame to change, however only the color changes when I do both. It appears that the UIButton.setTitleColor() interferes with the changing of the frame.


Solution

  • Instead of setting the UIButton's titleColor using setTitleColor(_:for:) method, change the color using button's titleLabel, i.e.

    UIView.animate(withDuration: 0.3) {
        self.nextButton.layer.opacity = 0.0
        self.signupButton.backgroundColor = UIColor(red: 75/255, green: 159/255, blue: 186/255, alpha: 1.0)
        self.signupButton.frame.size = CGSize(width: UIScreen.main.bounds.width - 69,height: 45)
        self.signupButton.titleLabel?.textColor = .white
    }