Sliders: class UISlider

A UISlider is an analog version of two digital control objects, the UIPageControl and UIStepper. With a

		print("slider.frame = \(slider.frame)");
I discovered that the slider’s height is 34 pairs of pixels in iPhone 6, iOS 8.1. But this fact is nowhere in Apple’s documentation, so it might change without warning in a future release. I set the slider’s width to 80% of the View’s width. Thanks to the UIViewAutoresizing.FlexibleWidth, the slider’s width will remain 80% of the View’s width, even in landscape orientation.

Source code in

  1. Class AppDelegate.swift: unchanged.
  2. Class ViewController: unchanged.
  3. Class View: added the methods init and valueChanged.

Things to try

  1. What happens when you set the continuous propery of the slider to false?

  2. In the init method of class View, specify the label’s font size as UIFont.labelFontSize() instead of as 26.

  3. Move the label up and down as the temperature changes. Add the following code to the valueChanged method of class View.
    		let margin: CGFloat = frame.size.height / 30;
    		//Range is the height (in pairs of pixels) of the range
    		//over which the position of the cener of the label will vary.
    		let range: CGFloat = (frame.size.height - label.frame.size.height) / 2 - 2 * margin;
    		//The fraction is in the range 0 to 1 inclusive.
    		//Convert Float to CGFloat.
    		let fraction: CGFloat =
    			CGFloat((slider.value - slider.minimumValue) / (slider.maximumValue - slider.minimumValue))
  = CGPointMake(
    			bounds.origin.x + frame.size.width / 2,
    			bounds.origin.y + frame.size.height / 2
    				+ slider.frame.size.height / 2 + margin
    				+ range * fraction);
    The initial position of the label should be halfway down the lower half of the View. And instead of creating margin in two different methods of class View, we should create it once and for all as a propery of the class.

  4. Make the slider vertical. Add the following statement to the init method of class View. We saw the affine transformations in Japan. Multiplication by π/180 converts degrees to radians. (We see a vertical slider on a Macintosh when we select the volume control in the Mac status bar.)
    	//Convert 90 degrees to radians.  Negative is counterclockwise.
    	//M_PI is Double, so we have to convert it explicitly to CGFloat.
    	let radians: CGFloat = CGFloat(-90 * M_PI / 180);
    	slider.transform = CGAffineTransformMakeRotation(radians);
    The label will have to be repositioned. Here’s an initial attempt you can start with.
    		//in layoutSubviews method of class View
    		label.frame = CGRectMake(
    			center.x - slider.frame.size.height / 2,
    			center.y + slider.frame.size.height / 2 + margin,

  5. Retrofit a slider volume control into Switch.