问题
I have project in which have to customise UISlider
element.
I wondering if someone knows how to change, or is it possible to change height of UISlide
bar line.
I tried something like this but don't work:
let customBounds = CGRect(origin: bounds.origin,
size: CGSize(width: bounds.size.width, height: 15.0))
feedbackSlider.trackRectForBounds(customBounds)
Thanks
回答1:
i hope that you want edit it in storyboard, and only the line size, use it in your custom UISlider
class CustomSlide: UISlider {
@IBInspectable var trackHeight: CGFloat = 2
override func trackRectForBounds(bounds: CGRect) -> CGRect {
//set your bounds here
return CGRect(origin: bounds.origin, size: CGSizeMake(bounds.width, trackHeight))
}
}
回答2:
You can override a method in you custom slider
For Objective-C
- (CGRect)trackRectForBounds:(CGRect)bounds {
CGRect rect = CGRectMake(0, 0, 100, 30);//change it to any size you want
return rect;
}
For Swift
override func trackRectForBounds(bounds: CGRect) -> CGRect {
var rect:CGRect = CGRectMake(0, 0, 100, 30)
return rect
}
回答3:
Overriding trackRect
is a way to go, however if you're using additional UISlider
's views like minimumValueImage, maximumValueImage
you would also need to take their bound into account, otherwise they will overlap with slider’s track. As a shortcut you can simply use super
's func:
Fixed version.
Swift 3+
@IBDesignable
class CustomSlider: UISlider {
/// custom slider track height
@IBInspectable var trackHeight: CGFloat = 3
override func trackRect(forBounds bounds: CGRect) -> CGRect {
// Use properly calculated rect
var newRect = super.trackRect(forBounds: bounds)
newRect.size.height = trackHeight
return newRect
}
}
回答4:
Swift 3
class MySlide: UISlider {
@IBInspectable var height: CGFloat = 2
override func trackRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: height))
}
}
回答5:
Swift 4 version without thumbImage.
class CustomSlider: UISlider {
@IBInspectable var trackHeight: CGFloat = 2
override func trackRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: trackHeight))
}
}
回答6:
You should be able to subclass the UISlider and then implement:
- (CGRect)trackRectForBounds:(CGRect)bounds
Just return the new CGRect here.
回答7:
U can easily get it done by subclassing UISlider
. see following code
class CustomUISlider : UISlider
{
override func trackRectForBounds(bounds: CGRect) -> CGRect {
//set your bounds here
return bounds
}
}
回答8:
If you're using autolayout
you can set a height
constraint on the UISlider
in the storyboard
. if you need to change it at runtime - create an IBOutlet
for the constraint and modify its .constant
value.
来源:https://stackoverflow.com/questions/31590188/how-to-customise-uislider-height