【发布时间】:2018-03-16 18:49:10
【问题描述】:
我发现我可以在导航栏上设置阴影图像,但我只想在滚动时设置它,而无法找到如何执行此操作。任何帮助表示赞赏!
【问题讨论】:
-
你有没有尝试过任何代码,然后发布它。
-
截图也会有帮助。
标签: ios swift uinavigationcontroller uinavigationbar
我发现我可以在导航栏上设置阴影图像,但我只想在滚动时设置它,而无法找到如何执行此操作。任何帮助表示赞赏!
【问题讨论】:
标签: ios swift uinavigationcontroller uinavigationbar
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
if offset <= 0 {
// scroll view is at the top, disable shadow
} else {
// scroll view has positive offset, enable shadow
}
print(offset) // if you aren't familiar with how it works
}
您可以从UIScrollView 或UITableView 访问此委托方法,因为后者是前者的子类。
【讨论】:
您可以将此代码与scrollViewDidScroll(_:) 一起使用:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "Hello"
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let navBar = navigationController?.navigationBar else {
return
}
if scrollView.contentOffset.y > navBar.frame.height {
addShadow(navBar)
} else {
deleteShadow(navBar)
}
}
func addShadow(_ view: UIView) {
view.layer.shadowColor = UIColor.gray.cgColor
view.layer.shadowOffset = CGSize(width: 0.0, height: 6.0)
view.layer.masksToBounds = false
view.layer.shadowRadius = 10.0
view.layer.shadowOpacity = 0.5
}
func deleteShadow(_ view: UIView) {
view.layer.shadowOffset = CGSize(width: 0, height: 0.0)
view.layer.shadowRadius = 0
view.layer.shadowOpacity = 0
}
}
【讨论】: