自定义UISlider(轨迹图像高度)

时间:2011-11-04 22:36:35

标签: iphone ios cocoa-touch uislider

我正在自定义UISlider。我可以设置一个高于通常拇指的自定义拇指图像,但是当设置更高的最小轨迹图像但轨道高度保持不变时,我无法使轨道更高。 应该可以像在iPad上的iPod /音乐应用程序中一样,音量滑块也像通常的滑块一样高,如下所示:

http://blog.cocoia.com/wp-content/uploads/2010/01/Lol-wut.png

5 个答案:

答案 0 :(得分:24)

您需要子类化滑块并覆盖trackRectForBounds:方法,如下所示:

- (CGRect)trackRectForBounds:(CGRect)bounds
{
    return bounds;
}

答案 1 :(得分:6)

Swift最简单的解决方案:

class TBSlider: UISlider {

    override func trackRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectMake(0, 0, bounds.size.width, 4)
    }
}

答案 2 :(得分:2)

使用下一个方法 setThumbImage setMinimumTrackImage setMaximumTrackImage

[self setThumbImage:[UIImage imageNamed:@"switchThumb.png"] forState:UIControlStateNormal];
    [self setMinimumTrackImage:[UIImage imageNamed:@"switchBlueBg.png"] forState:UIControlStateNormal];
    [self setMaximumTrackImage:[UIImage imageNamed:@"switchOffPlain.png"] forState:UIControlStateNormal];

并像这样创建子类

- (id) initWithFrame: (CGRect)rect{
    if ((self=[super initWithFrame:CGRectMake(rect.origin.x,rect.origin.y,90,27)])){
        [self awakeFromNib];
    }
    return self;
}

答案 3 :(得分:2)

对于那些希望看到一些改变音轨大小的工作代码的人。

class CustomUISlider : UISlider
{        
    override func trackRectForBounds(bounds: CGRect) -> CGRect {
        //keeps original origin and width, changes height, you get the idea
        let customBounds = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width, height: 5.0))
        super.trackRectForBounds(customBounds)
        return customBounds
    }

    //while we are here, why not change the image here as well? (bonus material)
    override func awakeFromNib() {
        self.setThumbImage(UIImage(named: "customThumb"), forState: .Normal)
        super.awakeFromNib()
    }
}

唯一剩下的就是更改故事板中的类:

storyboardstuff

除非您想在滑块上添加更多自定义内容,否则您可以继续使用搜索栏操作和插座来添加对象类型UISlider。

答案 4 :(得分:1)

//use this code

 UIImage *volumeLeftTrackImage = [[UIImage imageNamed: @"video_payer_scroll_selection.png"] stretchableImageWithLeftCapWidth: 9 topCapHeight: 0];
        UIImage *volumeRightTrackImage= [[UIImage imageNamed: @"video_bar_bg.png"] stretchableImageWithLeftCapWidth: 9 topCapHeight: 0];
        [volumeslider setMinimumTrackImage: volumeLeftTrackImage  forState: UIControlStateNormal];
        [volumeslider setMaximumTrackImage: volumeRightTrackImage  forState: UIControlStateNormal];
        [volumeslider setThumbImage:[UIImage imageNamed:@"sound_bar_btn.png"] forState:UIControlStateNormal];
        [tempview addSubview:volumeslider];