我们用两个label来显示slider和stepper的值.再用张图片来显示改变stepper值的效果.首先,这三个控件需要全局变量声明如下
var labelSlider = UILabel() var labelStepper = UILabel() var myImageView = UIImageView()
然后,我们对所有的控件做个简单的布局:
//创建label self.labelSlider.frame = CGRectMake(28.0,34.0,42.0,21.0) self.labelSlider.text = "0.50"; self.view.addSubview(self.labelSlider) self.labelStepper.frame=CGRectMake(206.0,285.0,79.0,21.0) self.labelStepper.text="iPhone4" self.view.addSubview(self.labelStepper) //创建slider var slider = UiSlider() slider.frame=CGRectMake(76.0,28.0,226.0,34.0) slider.minimumValue=0.0 slider.maximumValue=1.0 slider.value=0.5 slider.addTarget(self,action: "sliderValueChanged:",forControlEvents: UIControlEvents.ValueChanged) self.view.addSubview(slider) //创建stepper var stepper = UIStepper() stepper.frame=CGRectMake(206.0,218.0,0.0,0.0) stepper.minimumValue = 4 stepper.maximumValue = 7 stepper.addTarget(self,action: "stepperValueChanged:",forControlEvents: UIControlEvents.ValueChanged) self.view.addSubview(stepper) //创建ImageView self.myImageView.frame=CGRectMake(48.0,215.0,92.0,162.0) self.myImageView.image = UIImage(named: "iPhone") self.view.addSubview(self.myImageView)最后,当slider的值改变时,我们用一个label来显示值的变化,同样,用另一个label来显示stepper值的变化,并改变图片的大小:
func sliderValueChanged(sender:UiSlider) { self.labelSlider.text="\(sender.value)" } func stepperValueChanged(sender:UIStepper) { var value = sender.value; self.labelStepper.text = "\(value)" switch (value) { case 4: self.myImageView.frame = CGRectMake(48,215,92,162); break; case 5: self.myImageView.frame = CGRectMake(48,215-88,162+88); break; case 6: self.myImageView.frame = CGRectMake(48,215-88*2,162+88*2); break; case 7: self.myImageView.frame = CGRectMake(48,215-88*3,162+88*3); break; default: break; } }实现效果如下: