如何在scrollView contentOffset y更改时动态更改字体大小?

时间:2016-12-16 14:28:37

标签: ios swift uiscrollview swift3

我有UIScrollViewUILabel。当用户向上/向下滚动UILabel时,我想将UIScrollView大小从33.0动态更改为0.0,0.0到33。

我该怎么做?

@IBOutlet weak var myLabel : UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.delegate = self
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offset = scrollView.contentOffset.y
    let fontpointmath = (myLabel.font.pointSize / (offset / 100) - 15)

    if offset > 0 {
        if fontpointmath < 0 {
            myLabel.font =  UIFont(name: "Arial", size: 0.0)
        }else if fontpointmath > 33 {
            myLabel.font =  UIFont(name: "Arial", size: 33.0)
        }else{
            myLabel.font =  UIFont(name: "Arial", size: CGFloat(fontpointmath))
        }
    }

我当前的代码只允许字体大小约为15磅而不会更改为0.当用户再次向下滚动时,它也不会达到33。

1 个答案:

答案 0 :(得分:2)

请尝试使用transform而不是字体大小更改

override func viewDidLoad() {
    super.viewDidLoad()
    scrollView.delegate = self
    myLabel.font = UIFont(name: "Arial", size: 33.0)
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offset = scrollView.contentOffset.y
    let scale = min(max(1.0 - offset / 200.0, 0.0), 1.0)
    myLabel.transform = CGAffineTransform(scaleX: scale, y: scale)
}