How to make UISlider default thumb to be smaller like the ones in the iOS control center

UI Scuti picture UI Scuti · Feb 7, 2017 · Viewed 32.3k times · Source

I'm working on an app and I have a custom UISlider.
However, I'm having some issues on how to make the default thumb to appear smaller like the ones in the iOS control center.
Note that I want the same iOS thumb, not a custom thumb image. So far, I've tried thumbRect(forBounds...) but no luck.
Any suggestions?

Answer

Axel Guilmin picture Axel Guilmin · Apr 29, 2017

You can't change the size of the default thumb image, but UISlider has a method setThumbImage(_:for:) that will allow you to pass a similar, smaller image.

enter image description here

In your view controller viewDidLoad :

let image:UIImage? = // ...
yourSlider.setThumbImage(image, for: .normal)
yourSlider.setThumbImage(image, for: .highlighted) // Also change the image when dragging the slider

See Customizing the Slider’s Appearance of the API Reference.


On iOS10, the default thumb image appear to be no more than a bordered white circle with a thin shadow dropped under (if you don't set the thumbTintColor).

I use this snippet to generate a similar image that can be scaled down ;)

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = " \
<svg xmlns='http://www.w3.org/2000/svg' width='86' height='86'> \
<foreignObject width='100%' height='100%'> \
	<div xmlns='http://www.w3.org/1999/xhtml'> \
		<style> \
		#ios-uislider-thumb { \
		  -webkit-box-sizing: content-box; \
		  -moz-box-sizing: content-box; \
		  box-sizing: content-box; \
		  width: 66px; \
		  height: 66px; \
		  overflow: hidden; \
		  border: 1px solid #CCC; \
		  -webkit-border-radius: 33px; \
		  border-radius: 33px; \
		  background: #FFFFFF; \
		  -webkit-box-shadow: 0 6px 6px 0 rgba(0,0,0,0.2); \
		  box-shadow: 0 6px 6px 0 rgba(0,0,0,0.2); \
		  margin : 5px 10px 15px 10px; \
		} \
		</style> \
		<div id='ios-uislider-thumb'></div> \
	</div> \
</foreignObject> \
</svg> \
";
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {
  type: "image/svg+xml;charset=utf-8"
});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
  ctx.drawImage(img, 0, 0);
  DOMURL.revokeObjectURL(url);
};
img.src = url;
<canvas id="canvas" style="border:2px dotted black;" width="86" height="86"></canvas>