Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel Over UISlider Thumb

Tags:

objective-c

How can i put an UILabel over the thumb of UISlider...so that when i move the thumb....UILabel will also move....as it is on the thumb...

Any idea??

like image 405
Rony Avatar asked Aug 18 '10 10:08

Rony


2 Answers

extension UIImage {
    class func imageWithLabel(_ label: UILabel) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, 0)
        defer { UIGraphicsEndImageContext() }
        label.layer.render(in: UIGraphicsGetCurrentContext()!)
        return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
    }
}

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UIScrollViewDelegate
{

    func maskRoundedImage(image: UIImage, radius: CGFloat) -> UIImage {
           let imageView: UIImageView = UIImageView(image: image)
           let layer = imageView.layer
           layer.masksToBounds = true
           layer.cornerRadius = radius
           UIGraphicsBeginImageContext(imageView.bounds.size)
           layer.render(in: UIGraphicsGetCurrentContext()!)
           let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
           UIGraphicsEndImageContext()
           return roundedImage!
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

            let label = UILabel(frame: CGRect(x: 0, y: 0, width: 28, height: 28))
            label.backgroundColor = .black
            label.textAlignment = .center
            label.font =  label.font.withSize(12)
            label.text = String(Int(round( backlightSlider.value * 100 )))
            label.textColor = .white
            var image = UIImage.imageWithLabel(label)
            image = maskRoundedImage(image: image, radius: 14.0)
            backlightSlider.setThumbImage(image, for: .normal)
}
like image 127
dewers0723 Avatar answered Nov 15 '22 19:11

dewers0723


Same answer with swift3:

    let trackRect: CGRect  = slider.trackRect(forBounds: slider.bounds)
    let thumbRect: CGRect  = slider.thumbRect(forBounds: slider.bounds , trackRect: trackRect, value: slider.value)
    let x = thumbRect.origin.x + slider.frame.origin.x
    let y = slider.frame.origin.y - 20
    sliderLabel.center = CGPoint(x: x, y: y)
like image 29
Dania Delbani Avatar answered Nov 15 '22 19:11

Dania Delbani