gpt4 book ai didi

ios - 如何让图像出现在 Swift 的 UI PickerView 组件中?

转载 作者:IT王子 更新时间:2023-10-29 05:26:01 27 4
gpt4 key购买 nike

我正在尝试在 Swift PickerView 中使用图像。我不知道如何让图像实际出现在组件中。我知道如何使用带有 titleForRow 函数的字符串来执行此操作,但我不知道如何使用图像来执行此操作。到目前为止,这是我的代码:

import UIKit
class ViewController: UIViewController, UIPickerViewDelegate {

@IBOutlet weak var pickerView: UIPickerView!


var imageArray: [UIImage] = [UIImage(named: "washington.jpg")!,
UIImage(named: "berlin.jpg")!, UIImage(named: "beijing.jpg")!,
UIImage(named: "tokyo.jpg")!]



override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


// returns the number of 'columns' to display.
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{

return 1

}

// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

return imageArray.count
}



}// end of app

最佳答案

您将需要为 UIPickerViewDelegate 协议(protocol)实现更多的委托(delegate)方法。特别是 rowHeight 委托(delegate)方法和 viewForRow 委托(delegate)方法。

类似于:

// MARK: UIPickerViewDataSource

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

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 2
}

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


// MARK: UIPickerViewDelegate

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {

var myView = UIView(frame: CGRectMake(0, 0, pickerView.bounds.width - 30, 60))

var myImageView = UIImageView(frame: CGRectMake(0, 0, 50, 50))

var rowString = String()
switch row {
case 0:
rowString = “Washington”
myImageView.image = UIImage(named:"washington.jpg")
case 1:
rowString = “Beijing”
myImageView.image = UIImage(named:"beijing.jpg")
case 2:
default:
rowString = "Error: too many rows"
myImageView.image = nil
}
let myLabel = UILabel(frame: CGRectMake(60, 0, pickerView.bounds.width - 90, 60 ))
myLabel.font = UIFont(name:some font, size: 18)
myLabel.text = rowString

myView.addSubview(myLabel)
myView.addSubview(myImageView)

return myView
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

// do something with selected row
}

请注意,标签布局等仅用于演示,需要进行调整,或者最好使用自动布局等。

关于ios - 如何让图像出现在 Swift 的 UI PickerView 组件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27769246/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com