ios - 缩放 UIPageControl 的当前点并使其居中
问题描述
我对 UIPageControl 进行了子类化,以使其当前的点更大。
class CustomPageControl: UIPageControl {
override var currentPage: Int {
didSet {
updateDots()
}
}
func updateDots() {
let currentDot = subviews[currentPage]
let largeScaling = CGAffineTransform(scaleX: 3, y: 3)
subviews.forEach {
// apply the large scale of newly selected dot
// restore the normal scale of previously selected dot
$0.transform = $0 == currentDot ? largeScaling : .identity
}
}
}
我试过(在 iOS 12 上):
- 改变
frame
or没有效果center
。currentDot
- 将转换更改为包含 a
translatedBy(x: CGFloat, y: CGFloat)
无效。 像这里改变约束是使第一个点跳跃:
currentDot.translatesAutoresizingMaskIntoConstraints = false currentDot.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0) currentDot.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0)
解决方案
我自己重写了所有子视图约束,终于让它工作了。
// https://stackoverflow.com/a/55063316/1033581
class DefaultPageControl: UIPageControl {
override var currentPage: Int {
didSet {
updateDots()
}
}
override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
super.sendAction(action, to: target, for: event)
updateDots()
}
private func updateDots() {
let currentDot = subviews[currentPage]
let largeScaling = CGAffineTransform(scaleX: 3.0, y: 3.0)
let smallScaling = CGAffineTransform(scaleX: 1.0, y: 1.0)
subviews.forEach {
// Apply the large scale of newly selected dot.
// Restore the small scale of previously selected dot.
$0.transform = $0 == currentDot ? largeScaling : smallScaling
}
}
override func updateConstraints() {
super.updateConstraints()
// We rewrite all the constraints
rewriteConstraints()
}
private func rewriteConstraints() {
let systemDotSize: CGFloat = 7.0
let systemDotDistance: CGFloat = 16.0
let halfCount = CGFloat(subviews.count) / 2
subviews.enumerated().forEach {
let dot = $0.element
dot.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.deactivate(dot.constraints)
NSLayoutConstraint.activate([
dot.widthAnchor.constraint(equalToConstant: systemDotSize),
dot.heightAnchor.constraint(equalToConstant: systemDotSize),
dot.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0),
dot.centerXAnchor.constraint(equalTo: centerXAnchor, constant: systemDotDistance * (CGFloat($0.offset) - halfCount))
])
}
}
}
代码中的系统常量(7.0 和 16.0)分别是 iOS 12 上默认 UIPageControl 点的大小和距离。
推荐阅读
- google-cloud-platform - 从永久性磁盘到 Google 存储桶的同步速度很慢
- javascript - 嘿,谁能告诉我为什么我不从 api 渲染数据
- lotus-domino - 如何防止浏览器暴露 Notes 视图
- java - 杰克逊的@JsonPropertyOrder 不适用于@JsonUnwrapped
- r - R 并行作业挂起
- vhdl - 我可以在多个模块实例上以别名聚合信号吗?
- java - 使用 Java HttpClient 的持久连接(保持活动状态)
- c# - 当另一个用户打开事务时在数据库上添加表
- node.js - Node Express 强制所有静态路由指向根路径
- python - 按列的唯一值绘制