UISlider滑块大小与高度的自定义

需求:

需要自定义UISlider的高度及滑块大小(UISlider滑动条的高度及滑块大小系统默认给我们设定了,没有办法进行改变。)

方法:

滑块大小可以通过设置滑块图片,图片大小为滑块需要大小实现;滑块高度需要写一个UISlider的子类,重写系统方法

代码:

下面代码在自定义Slider中将高度固定死,若要复用可通过增加高度属性完成

OC版本:

// MXSlider.h
#import 

@interface MXSlider : UISlider

@end


//  MXSlider.m
#import "MXSlider.h"

@implementation MXSlider

// 控制slider的宽和高,这个方法才是真正的改变slider滑道的高的
- (CGRect)trackRectForBounds:(CGRect)bounds
{
    bounds.size.height=6;
    self.layer.cornerRadius = 2.5;
    return bounds;
}

// 改变滑块的触摸范围
- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value
{    
    rect.origin.x = rect.origin.x - 5 ;
    rect.size.width = rect.size.width +10;
    return CGRectInset ([super thumbRectForBounds:bounds trackRect:rect value:value], 5 , 5);
}

@end

swift版本:

import UIKit

class CustomSlider: UISlider {
    
    var sliderHeight: CGFloat = 4.0
    
    override func minimumValueImageRect(forBounds bounds: CGRect) -> CGRect {
        return self.bounds
    }
    
    override func maximumValueImageRect(forBounds bounds: CGRect) -> CGRect {
        return self.bounds
    }
    
    // 控制slider的宽和高,这个方法才是真正的改变slider滑道的高的
    override func trackRect(forBounds bounds: CGRect) -> CGRect {
        let rect = super.trackRect(forBounds: bounds)
        layer.cornerRadius = sliderHeight/2
        return CGRect.init(x: rect.origin.x, y: (bounds.size.height-sliderHeight)/2, width: bounds.size.width, height: sliderHeight)
    }
    
    // 改变滑块的触摸范围
    override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
        return super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
    }
    
}

调用:

// slider
self.playSlider = [[MXSlider alloc] initWithFrame:CGRectMake(84, ScreenHeight-SafeBottom-37-5, ScreenWidth-84-55, 5)];
self.playSlider.value = 0;
self.playSlider.thumbTintColor = [UIColor whiteColor];
// 区域颜色
self.playSlider.minimumTrackTintColor = [UIColor whiteColor];
self.playSlider.maximumTrackTintColor = rgba(0, 0, 0, 0.3);
//
[self.playSlider setThumbImage:[UIImage imageNamed:@"music_btn_dot"] forState:UIControlStateNormal];
[self.playSlider setThumbImage:[UIImage imageNamed:@"music_btn_dot"] forState:UIControlStateHighlighted];
[self.playSlider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:_playSlider];

 

参考文章:

修改系统的UISlider 高度

iOS控件-UISlider滑动单位精确度与UISlider高度研究

你可能感兴趣的:(UISlider滑块大小与高度的自定义)