滚动tableView时动态更改标签的字体大小

时间:2019-03-02 08:55:31

标签: swift scroll label font-size

我有tableView并在其上面有imageView。通过本指南https://github.com/abhimuralidharan/StretchableTableViewHeader-Swift制作了可伸缩的标头 现在,我必须在图像上添加标签。滚动tableView时,此标签应更改大小/字体。

我在另一个类中创建了imageView:

class LotteryHeaderView: UIImageView {

let ticketsCountLabel: UILabel = {
    let label = UILabel()
    label.textColor = .white
    label.translatesAutoresizingMaskIntoConstraints = false
    label.font = UIFont.boldSystemFont(ofSize: 100)
    return label
}()

let infoLabel: UILabel = {
    let label = UILabel()
    label.textColor = .white
    label.textAlignment = .center
    label.translatesAutoresizingMaskIntoConstraints = false
    label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
    label.numberOfLines = 2
    label.text = Localizable.all_user_tickets_count()
    return label
}()

override init(frame: CGRect) {
    super.init(frame: frame)
    self.addSubViews([ticketsCountLabel, infoLabel])

    ticketsCountLabel.centerX(to: self.centerXAnchor)
        .centerY(to: self.centerYAnchor)

    infoLabel.top(to: ticketsCountLabel.bottomAnchor, constant: 7)
        .width(constant: 184)
        .centerX(to: self.centerXAnchor)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}    

}

在我的控制器中将其初始化:

let imageView = LotteryHeaderView(frame: CGRect(x: 0, y: 0, width: Constants.Size.screenWidth, height: 300))

在viewDidLoad中设置:

imageView.frame = CGRect(x: 0, y: 0, width: Constants.Size.screenWidth, height: 300)
    imageView.image = R.image.santa_fe()
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true
    view.addSubview(imageView)

在这里func每次滚动tableview时都会被调用,它适用于我的图像(可折叠和可拉伸):

func scrollImageInHeader(scrollView: UIScrollView) {
    let y = 300 - (scrollView.contentOffset.y + 300)
    let height = min(max(y, 60), 450)
    imageView.frame = CGRect(x: 0, y: 0, width: Constants.Size.screenWidth, height: height)
}

试图在this StackOverFlowAnswer的下面添加scrollImageInHeader()代码,但这无济于事

let offset = scrollView.contentOffset.y
    let scale = min(max(1.0 - offset / 200.0, 0.0), 1.0)
    imageView.ticketsCountLabel.transform = CGAffineTransform(scaleX: scale, y: scale)

请帮助我们。

2 个答案:

答案 0 :(得分:0)

UIScrollView是父级UITableViewController。您可以将UIScrollView和UIScrollViewDelegate一起使用,以带有scrollOffset的设置标签字体大小:CGFloat follow .y

extension ViewController: UIScrollViewDelegate{
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var scrollOffset : CGFloat = scrollView.contentOffset.y
    // process with scrollOffset
  }
}

答案 1 :(得分:0)

实际上我发现了我的错误。来自Here的代码有所帮助。 类LotteryHeaderView我更改为UIView并在其中添加了UIImageView。