简体   繁体   中英

How to add images or icons next to a text in UIPickerView in Swift 4?

I made it this far and it replies my text without a problem:

    class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var foodLabel: UILabel!
    @IBOutlet weak var foodSlider: UIPickerView!

    var picker = UIPickerView()

    let foodsScroll = ["pizza \npepperoni" ,"chicken \nnuggets ","meat \nballs","hamburger \nbloody","omelette \ngrilled","ice cream \nberry"]

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 80.00
    }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

        let cgRect = CGRect(x: 0.00, y: 0.00, width: 400, height: 200)
        let label = UILabel(frame: cgRect)
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = 0
        label.text = foodsScroll[row]
        label.sizeToFit()
        return label
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return foodsScroll[row]
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        return foodsScroll.count
    }


    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        foodLabel.text = foodsScroll[row]
    }

    override func viewDidLoad() {

    }

}

And it comes to the part where I need to add a single icon to one side of each food's name. I can't quite figure out how it's done, but I know you can use 2 simple ways of:

  1. Using an extra UIView and
  2. Using an UIImage.

Any alternative methods are also welcome.

You are the question and you are the answer Yes!! here two simple way to add your idea 1)using an extra UIView and 2)using an UIImage. 3)create a card And finally it's one here it's card. but it's same as UIView

https://github.com/aclissold/CardView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM