将字符串委托给 UILabel,将图像委托给 UIImageView - Swift
Delegating a string to a UILabel and an image to a UIImageView - Swift
所以,这就是正在发生的事情:我有两个控制器; MainViewController 和 DetailsTableViewController。在 DetailsTableViewController 上,我想为随机食谱写一个名称,然后我从照片库中选择一张图片。之后,我想将这些数据发送到 MainViewController 中的一个单元格。代码如下:
import UIKit
import CoreData
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, sendDetailsToMVCDelegate {
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var tableView: UITableView!
var namesListArray: [String] = []
var imagesListArray: [UIImage] = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func sendDetailsToMVC (name: String, image: UIImage) {
namesListArray.append(name)
imagesListArray.append(image)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return namesListArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var row = indexPath.row
var name: String = namesListArray[row] as String
var image: UIImage = imagesListArray[row] as UIImage
var cell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as! CustomCellTableViewCell
cell.customLabel!.text = (name as String)
cell.customImage.image = (image as UIImage)
return cell
}
}
和
import UIKit
import CoreData
protocol sendDetailsToMVCDelegate {
func sendDetailsToMVC(name: String, image: UIImage)
}
class DetailsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDataSource, UITableViewDelegate, sendNameToDetailsViewControllerDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var recipeImage: UIImageView!
@IBOutlet weak var tableView: UITableView!
var ingredientsList = [""]
var delegateDetails: sendDetailsToMVCDelegate?
override func viewDidLoad() {
super.viewDidLoad()
let howToDoButton = UIBarButtonItem(title:"How To Do", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("showHowToDoScreen"))
navigationItem.rightBarButtonItem = howToDoButton
let newIngredientButton = UIBarButtonItem(title:"New Ingredient", style: UIBarButtonItemStyle.Plain, target:self, action: Selector("showNewIngredientScreen"))
navigationItem.leftBarButtonItem = newIngredientButton
//Picker imagem pelo toque
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "chooseImage:")
tapGestureRecognizer.numberOfTapsRequired = 1
recipeImage.addGestureRecognizer(tapGestureRecognizer)
recipeImage.userInteractionEnabled = true
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ingredientsList.count
}
func addNameToDetailsViewController(nameToDetail: NSString) {
ingredientsList.append(nameToDetail as String)
if tableView == nil {
return
}
tableView!.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
let ingredientName = ingredientsList[row]
var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.textLabel!.text = ingredientName
return cell
}
//Picka a imagem pelo toque, acessando a PhotoLibrary
func chooseImage(recognizer: UITapGestureRecognizer) {
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
}
//Ao selecionar a imagem, coloca-a na tela tocada
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject:AnyObject]) {
let pickedImage: UIImage = (info as NSDictionary).objectForKey(UIImagePickerControllerOriginalImage) as! UIImage
// small picture
let smallPicture = scaleImageWith(pickedImage, newSize: CGSizeMake(75,75))
var sizeOfImageView:CGRect = recipeImage.frame
sizeOfImageView.size = smallPicture.size
recipeImage.frame = sizeOfImageView
recipeImage.image = smallPicture
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil)
}
func scaleImageWith(image:UIImage, newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.drawInRect(CGRectMake(0,0, newSize.width, newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
@IBAction func showNewIngredientScreen() {
let newIngredient = AddIngredientViewController(delegate: self)
if let navigation = navigationController {
navigation.pushViewController(newIngredient, animated: true)
}
}
@IBAction func showHowToDoScreen() {
let howToDo = HowToDoViewController(nibName: "HowToDoViewController", bundle: nil)
if let navigation = navigationController {
navigation.pushViewController(howToDo, animated: true)
}
}
@IBAction func addButton(sender: AnyObject) {
if nameTextField == nil || recipeImage == nil { return }
if recipeImage == nil { return }
let nameLabel = nameTextField.text
let imageView = recipeImage.image
if delegateDetails == nil { return }
delegateDetails?.sendDetailsToMVC(nameLabel, image: imageView!)
println("button pressed, name \(nameLabel) and image \(imageView) added.")
if let navigation = self.navigationController {
navigation.popViewControllerAnimated(true)
}
}
我的问题是:我传递的信息是否正确?存储图像的正确方法是否像我一样创建图像数组?当我按下 addButton 时,没有任何反应,但它没有崩溃。我在这个问题上已经有一段时间了,如果有人指出我出了什么问题,我将非常感激。
顺便说一下,我是 Swift 的新手,所以请原谅我的任何 n00b 错误。
谢谢!
应该与您的 中的相同。在 addButton
函数中,如果不是 nil
而不是应该设置委托,则只设置委托。所以从 DetailViewControler - addButton 中删除 if delegateDetails == nil { return }
它应该可以工作。
所以,这就是正在发生的事情:我有两个控制器; MainViewController 和 DetailsTableViewController。在 DetailsTableViewController 上,我想为随机食谱写一个名称,然后我从照片库中选择一张图片。之后,我想将这些数据发送到 MainViewController 中的一个单元格。代码如下:
import UIKit
import CoreData
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, sendDetailsToMVCDelegate {
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var tableView: UITableView!
var namesListArray: [String] = []
var imagesListArray: [UIImage] = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func sendDetailsToMVC (name: String, image: UIImage) {
namesListArray.append(name)
imagesListArray.append(image)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return namesListArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var row = indexPath.row
var name: String = namesListArray[row] as String
var image: UIImage = imagesListArray[row] as UIImage
var cell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as! CustomCellTableViewCell
cell.customLabel!.text = (name as String)
cell.customImage.image = (image as UIImage)
return cell
}
}
和
import UIKit
import CoreData
protocol sendDetailsToMVCDelegate {
func sendDetailsToMVC(name: String, image: UIImage)
}
class DetailsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDataSource, UITableViewDelegate, sendNameToDetailsViewControllerDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var recipeImage: UIImageView!
@IBOutlet weak var tableView: UITableView!
var ingredientsList = [""]
var delegateDetails: sendDetailsToMVCDelegate?
override func viewDidLoad() {
super.viewDidLoad()
let howToDoButton = UIBarButtonItem(title:"How To Do", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("showHowToDoScreen"))
navigationItem.rightBarButtonItem = howToDoButton
let newIngredientButton = UIBarButtonItem(title:"New Ingredient", style: UIBarButtonItemStyle.Plain, target:self, action: Selector("showNewIngredientScreen"))
navigationItem.leftBarButtonItem = newIngredientButton
//Picker imagem pelo toque
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "chooseImage:")
tapGestureRecognizer.numberOfTapsRequired = 1
recipeImage.addGestureRecognizer(tapGestureRecognizer)
recipeImage.userInteractionEnabled = true
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ingredientsList.count
}
func addNameToDetailsViewController(nameToDetail: NSString) {
ingredientsList.append(nameToDetail as String)
if tableView == nil {
return
}
tableView!.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
let ingredientName = ingredientsList[row]
var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.textLabel!.text = ingredientName
return cell
}
//Picka a imagem pelo toque, acessando a PhotoLibrary
func chooseImage(recognizer: UITapGestureRecognizer) {
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
}
//Ao selecionar a imagem, coloca-a na tela tocada
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject:AnyObject]) {
let pickedImage: UIImage = (info as NSDictionary).objectForKey(UIImagePickerControllerOriginalImage) as! UIImage
// small picture
let smallPicture = scaleImageWith(pickedImage, newSize: CGSizeMake(75,75))
var sizeOfImageView:CGRect = recipeImage.frame
sizeOfImageView.size = smallPicture.size
recipeImage.frame = sizeOfImageView
recipeImage.image = smallPicture
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil)
}
func scaleImageWith(image:UIImage, newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.drawInRect(CGRectMake(0,0, newSize.width, newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
@IBAction func showNewIngredientScreen() {
let newIngredient = AddIngredientViewController(delegate: self)
if let navigation = navigationController {
navigation.pushViewController(newIngredient, animated: true)
}
}
@IBAction func showHowToDoScreen() {
let howToDo = HowToDoViewController(nibName: "HowToDoViewController", bundle: nil)
if let navigation = navigationController {
navigation.pushViewController(howToDo, animated: true)
}
}
@IBAction func addButton(sender: AnyObject) {
if nameTextField == nil || recipeImage == nil { return }
if recipeImage == nil { return }
let nameLabel = nameTextField.text
let imageView = recipeImage.image
if delegateDetails == nil { return }
delegateDetails?.sendDetailsToMVC(nameLabel, image: imageView!)
println("button pressed, name \(nameLabel) and image \(imageView) added.")
if let navigation = self.navigationController {
navigation.popViewControllerAnimated(true)
}
}
我的问题是:我传递的信息是否正确?存储图像的正确方法是否像我一样创建图像数组?当我按下 addButton 时,没有任何反应,但它没有崩溃。我在这个问题上已经有一段时间了,如果有人指出我出了什么问题,我将非常感激。
顺便说一下,我是 Swift 的新手,所以请原谅我的任何 n00b 错误。
谢谢!
应该与您的 addButton
函数中,如果不是 nil
而不是应该设置委托,则只设置委托。所以从 DetailViewControler - addButton 中删除 if delegateDetails == nil { return }
它应该可以工作。