UIImageView 不连续

Posted

技术标签:

【中文标题】UIImageView 不连续【英文标题】:UIImageView not segueing 【发布时间】:2016-02-16 10:49:03 【问题描述】:

我的NewsTableViewController.swift 中有一个UIImageView (0x0),它与NewsDetailTableViewController.swift 相连,其中UIImageView 是600x216。

如果你问为什么第一个 UIImageView 是 0x0,那是因为这是我知道如何通过每个单元格分隔不同图像的唯一方法。我的主 VC 中有 16 个单元格,每个细节 VC 都有不同的图像。我不想在主 VC 的单元格中显示图像。

如果你能建议另一种方式,那就太好了。

无论如何,保持这个解决方案,我的 segue 有什么问题?这些图像存储在一个名为 detailImages 的数组中。这个数组在NewsTableViewController.swift

这是我的NewsDetailTableViewController.swift

UIImageView 应该是标题和内容之间的空白位置。

这是我的NewsTableViewController.swift 中的prepareForSegue 方法:

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)

    if segue.identifier == "showDetail" 

        if let indexPath = tableView.indexPathForSelectedRow 
            let destinationController = segue.destinationViewController as! NewsDetailTableViewController
            destinationController.item = items[indexPath.row]
            //destinationController.imageNames = detailImages
        
    

这是我的NewsDetailTableViewController.swift 代码:

import UIKit

class NewsDetailTableViewController: UITableViewController 

var items = [Item]()
var item:Item!
var siteURL = "http://annabellesykes.netau.net/shailenewoodleyfansappjson.json"
var image:UIImageView!
@IBOutlet weak var segueImageView:UIImageView!

override func viewDidLoad() 
    super.viewDidLoad()

    title = "News"
    navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
    getLatestNews()

    tableView.estimatedRowHeight = 400.0
    tableView.rowHeight = UITableViewAutomaticDimension

    tableView.separatorStyle = UITableViewCellSeparatorStyle.None




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


// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int 
    return 1


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    return 1


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NewsDetailTableViewCell

    // Configure the cell...
    cell.newsDetailTitle.text = item.title
    cell.newsDetailDate.text = item.date
    cell.newsDetailContent.text = item.content
    cell.newsDetailImageView.image = UIImage()

    cell.newsDetailTitle.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.newsDetailTitle.numberOfLines = 999
    cell.newsDetailContent.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.newsDetailContent.numberOfLines = 999

    cell.newsDetailTitle.sizeToFit()
    cell.newsDetailContent.sizeToFit()

    return cell


override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
    return UITableViewAutomaticDimension


override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
    return UITableViewAutomaticDimension


func getLatestNews() 

    let request = NSURLRequest(URL: NSURL(string: siteURL)!)
    let urlSession = NSURLSession.sharedSession()
    let task = urlSession.dataTaskWithRequest(request, completionHandler: 
        (data, response, error) -> Void in

        if let error = error 
            print(error)
            return
        

        if let data = data 
            self.items = self.parseJsonData(data)

            NSOperationQueue.mainQueue().addOperationWithBlock( () -> Void in
                self.tableView.reloadData()
            )
        

    )

    task.resume()


func parseJsonData(data: NSData) -> [Item] 

    var items = [Item]()

    do 

        let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary

        let jsonItems = jsonResult?["items"] as! [AnyObject]
        for jsonItem in jsonItems 
            let item = Item()
            item.title = jsonItem["title"] as! String
            item.content = jsonItem["content"] as! String
            item.date = jsonItem["date"] as! String
            items.append(item)
        

     catch 
        print(error)
    

    return items




这是我的NewsTableViewController.swift

import UIKit

class NewsTableViewController: UITableViewController 

var siteURL = "http://annabellesykes.netau.net/shailenewoodleyfansappjson.json"
var items = [Item]()
var item:Item!
var newsImage:UIImageView?

@IBOutlet weak var imageHeaderView1:UIImageView!

var detailImages = ["newsimage1.jpg", "newsimage2.jpg", "newsimage3.jpg", "newsimage4.jpg", "newsimage5.jpg", "newsimage6.jpg", "newsimage7.jpg", "newsimage8.jpg", "newsimage9.jpg", "newsimage10.jpg", "newsimage10.jpg", "newsimage11.jpg", "newsimage12.jpg", "newsimage13.jpg", "newsimage14.jpg", "newsimage15.jpg", "newsimage16.jpg"]

override func viewDidLoad() 
    super.viewDidLoad()

    getLatestNews()
    navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)


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


// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int 
    return 1


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    return items.count


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NewsTableViewCell

    // Configure the cell...
    cell.titleLabel.text = items[indexPath.row].title
    cell.dateLabel.text = items[indexPath.row].date
    cell.contentLabel.text = items[indexPath.row].content
    cell.newsImageView.image = UIImage(named: detailImages[indexPath.row])

    cell.titleLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.titleLabel.numberOfLines = 999
    cell.contentLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.contentLabel.numberOfLines = 3
    cell.dateLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
    cell.dateLabel.numberOfLines = 999

    cell.dateLabel.sizeToFit()

    //cell.imageView?.image = self.imageNames[indexPath.row]

    return cell


override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction] 

    let shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Share", handler:  (action, indexPath) -> Void in

        let defaultText = "Check this out: " + self.items[indexPath.row].title + "! " + self.items[indexPath.row].content
        let activityController = UIActivityViewController(activityItems: [defaultText], applicationActivities: nil)
        self.presentViewController(activityController, animated: true, completion: nil)
    )

    shareAction.backgroundColor = UIColor(red: 179.0/255.0, green: 239.0/255.0, blue:  247.0/255.0, alpha: 1.0)

    return [shareAction]


override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
    cell.alpha = 0
    UIView.animateWithDuration(1.0, animations:  cell.alpha = 1 )


func getLatestNews() 

    let request = NSURLRequest(URL: NSURL(string: siteURL)!)
    let urlSession = NSURLSession.sharedSession()
    let task = urlSession.dataTaskWithRequest(request, completionHandler: 
        (data, response, error) -> Void in

        if let error = error 
            print(error)
            return
        

        if let data = data 
            self.items = self.parseJsonData(data)

            NSOperationQueue.mainQueue().addOperationWithBlock( () -> Void in
                self.tableView.reloadData()
            )
        

    )

    task.resume()


func parseJsonData(data: NSData) -> [Item] 

    var items = [Item]()

    do 

        let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary

        let jsonItems = jsonResult?["items"] as! [AnyObject]
        for jsonItem in jsonItems 
            let item = Item()
            item.title = jsonItem["title"] as! String
            item.content = jsonItem["content"] as! String
            item.date = jsonItem["date"] as! String
            items.append(item)
        

     catch 
        print(error)
    

    return items


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)

    if segue.identifier == "showDetail" 

        if let indexPath = tableView.indexPathForSelectedRow 
            let destinationController = segue.destinationViewController as! NewsDetailTableViewController
            destinationController.item = items[indexPath.row]
            destinationController.image = UIImageView(image: UIImage(named: detailImages[indexPath.row]))
        
    


@IBAction func unwindToHomeScreen(segue: UIStoryboardSegue) 



【问题讨论】:

【参考方案1】:

您的cellForRowAtIndexPath 中的NewsDetailTableViewController.swift 中的图像似乎没有正确设置。

尤其是这一行:

cell.newsDetailImageView.image = UIImage()

【讨论】:

这条线我该怎么办? 这是你应该设置你的图像的地方,使用detailImages的内容。但是查看您的代码,您似乎在NewsDetailTableViewController.swift 中没有一个名为detailImages 的数组。您要显示的图像存储在哪里? 存储在NewsTableViewController.swift 好吧,我的错。所以你有一个图像数组,你想将一个特定的图像传递给NewsDetailTableViewController.swift。我想你可以在NewsDetailTableViewController.swift 上创建一个UIImage 变量并将其设置在prepareForSegue 中。我假设该值为detailImages[indexPath.row] 我该如何写这个?喜欢destinationController.image = UIImage(named: detailImages[indexPath.row])【参考方案2】:
Here is code in objective c... 
#pragma Mark Prepare For Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 

    if ([segue.identifier isEqualToString:@"segue"]) 

    viewcontroller *destViewController = segue.destinationViewController;
        destViewController.image=[[Apparels objectAtIndex:0];

        


//In other class 
@property (strong, nonatomic) NSString *image;
   UIImageView.image=[UIImage imageNamed:image];

【讨论】:

我使用的是 swift,而不是 Obj-C。

以上是关于UIImageView 不连续的主要内容,如果未能解决你的问题,请参考以下文章

使 UIImageview 根据另一个 UIImageview 旋转而旋转

在 UIScrollView 中放大多个 UIImageView

更改 UIImageView 大小以匹配图像与 AutoLayout

在 UIScrollView 内的 UIImageView 上启用 GestureRegnizer

如何防止 UIImageView 使用 Autolayout 调整大小

UIImageView 在我设置图像时移动或调整大小