gpt4 book ai didi

ios - 自定义 PageControl 图像 - Swift

转载 作者:可可西里 更新时间:2023-11-01 00:39:33 28 4
gpt4 key购买 nike

我正在尝试为 UIPageControl 点设置图像。

我需要更改默认点,而不是我需要一张图片。我使用了下面的代码

self.pageCtrl.currentPageIndicatorTintColor = UIColor.init(patternImage: UIImage(named: "Page Indicator_Selected")!)
self.pageCtrl.pageIndicatorTintColor = UIColor.init(patternImage: UIImage(named: "Page Indicator_Normal")!)

我可以在 Pagecontrol 中设置图像,但它与默认点重叠。

最佳答案

Politta 建议的代码不适用于 iOS 14,因为 Apple 为 UIPageControll 引入了一些新的 API。

详情看这里UIPageControls New APIs

这是支持 iOS 14 的更新代码

class CustomPageControl: UIPageControl {

@IBInspectable var currentPageImage: UIImage?

@IBInspectable var otherPagesImage: UIImage?

override var numberOfPages: Int {
didSet {
updateDots()
}
}

override var currentPage: Int {
didSet {
updateDots()
}
}

override func awakeFromNib() {
super.awakeFromNib()
if #available(iOS 14.0, *) {
defaultConfigurationForiOS14AndAbove()
} else {
pageIndicatorTintColor = .clear
currentPageIndicatorTintColor = .clear
clipsToBounds = false
}
}

private func defaultConfigurationForiOS14AndAbove() {
if #available(iOS 14.0, *) {
for index in 0..<numberOfPages {
let image = index == currentPage ? currentPageImage : otherPagesImage
setIndicatorImage(image, forPage: index)
}

// give the same color as "otherPagesImage" color.
pageIndicatorTintColor = .gray

// give the same color as "currentPageImage" color.
currentPageIndicatorTintColor = .red
/*
Note: If Tint color set to default, Indicator image is not showing. So, give the same tint color based on your Custome Image.
*/
}
}

private func updateDots() {
if #available(iOS 14.0, *) {
defaultConfigurationForiOS14AndAbove()
} else {
for (index, subview) in subviews.enumerated() {
let imageView: UIImageView
if let existingImageview = getImageView(forSubview: subview) {
imageView = existingImageview
} else {
imageView = UIImageView(image: otherPagesImage)

imageView.center = subview.center
subview.addSubview(imageView)
subview.clipsToBounds = false
}
imageView.image = currentPage == index ? currentPageImage : otherPagesImage
}
}
}

private func getImageView(forSubview view: UIView) -> UIImageView? {
if let imageView = view as? UIImageView {
return imageView
} else {
let view = view.subviews.first { (view) -> Bool in
return view is UIImageView
} as? UIImageView

return view
}
}
}

关于ios - 自定义 PageControl 图像 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47279137/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com