问题
I have a custom UISlider, but there is a side of the slider which is not rounded
Here my custom view:
class PrimarySliderView: UISlider {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override func trackRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: 6))
}
func setup() {
tintColor = .cornFlowerBlue
}
How to round the right side also?
EDIT
The slider is cutted because my application is RTL, when I change to LTR this display correctly but not in RTL, how to resolve this problem?
In My AppDelegate I force RTL:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UIView.appearance().semanticContentAttribute = .forceRightToLeft
return true
}
回答1:
Either you need to add rounded image for minimum and maximum track or you can create rounded view using colors
other workaround is
override func layoutSubviews() {
super.layoutSubviews()
self.layer.sublayers![1].cornerRadius = 10
}
回答2:
try this one
if(UIApplication.sharedApplication().userInterfaceLayoutDirection == UIUserInterfaceLayoutDirection.RightToLeft)
{
uiSlider.transform = CGAffineTransformMakeScale(-1.0, 1.0);
}
回答3:
Here is a solution/workaround and it works with iOS 14 based on this answer. Also, it is tweaked to solve blurry edges.
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
setMinimumTrackImage(getImageWithColor(color: .blue, size: frame.size).resizableImage(withCapInsets: UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3), resizingMode: .stretch), for: .normal)
}
And here is the implementation of getImageWithColor:
private func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
let layer: CALayer = CALayer()
layer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
layer.masksToBounds = true
layer.cornerRadius = 3
layer.backgroundColor = color.cgColor
UIGraphicsBeginImageContextWithOptions(size, false, 0)
layer.render(in: UIGraphicsGetCurrentContext()!)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
NOTE: Don't forget to change cornerRadius and UIEdgeInsets to suit your needs.
Before applying the fix:
After applying the fix:
来源:https://stackoverflow.com/questions/59948677/swift-uislider-one-side-of-track-not-rounded