Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 将额外的单元格添加为";请参阅“更多”;如果计数为>;8在集合视图单元格中_Ios_Swift_Uicollectionview - Fatal编程技术网

Ios 将额外的单元格添加为";请参阅“更多”;如果计数为>;8在集合视图单元格中

Ios 将额外的单元格添加为";请参阅“更多”;如果计数为>;8在集合视图单元格中,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,我有一个UICollectionView。我正在从我的URL在我的集合视图中动态显示单元格。我设置了一行中只有4个单元格的单元格宽度和高度。所以现在从我的url,我得到了总共14个项目。我指的是14个标签名称和14个标签图像。因此,总共有14项必须显示在我的表视图中 但我需要的是:我只需要在集合视图中显示两行,然后设置单元格的宽度和高度。所以每行4项意味着,两行共8项。但是从我的URL我得到了14个项目,对吗 所以,我需要的是-如果项目数超过7。我在数表0到表7。然后我需要将第七个单元格显示为静

我有一个UICollectionView。我正在从我的URL在我的集合视图中动态显示单元格。我设置了一行中只有4个单元格的单元格宽度和高度。所以现在从我的url,我得到了总共14个项目。我指的是14个标签名称和14个标签图像。因此,总共有14项必须显示在我的表视图中

但我需要的是:我只需要在集合视图中显示两行,然后设置单元格的宽度和高度。所以每行4项意味着,两行共8项。但是从我的URL我得到了14个项目,对吗

所以,我需要的是-如果项目数超过7。我在数表0到表7。然后我需要将第七个单元格显示为静态的。文本应该自动更改为“查看更多”

怎么做

import UIKit

class HomeViewController: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate {


    @IBOutlet weak var collectionView1: UICollectionView!


    var BTdata = [BTData]()


    override func viewDidLoad()
    {
        super.viewDidLoad()

        ListBusinessTypes()

    }

    // Values from Api for Business Types
    func ListBusinessTypes()
    {
        let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String

        let headers = ["x-access-token": token]

        let request = NSMutableURLRequest(URL: NSURL(string: “some url“)!,
                                          cachePolicy: .UseProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.HTTPMethod = "GET"
        request.allHTTPHeaderFields = headers

        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
            if (error != nil)
            {
                print(error)

                let ErrorAlert = UIAlertController(title: "Error", message: "Problem with internet connectivity or server, please try after some time", preferredStyle: UIAlertControllerStyle.Alert)

                // add an action (button)
                ErrorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                // show the alert
                self.presentViewController(ErrorAlert, animated: true, completion: nil)
            }
            else
            {
                if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
                {
                    let success = json["success"] as? Int

                    if(success == 1)
                    {

                        if let typeValues = json["data"] as? [NSDictionary]
                        {
                            dispatch_async(dispatch_get_main_queue(),{

                                for item in typeValues
                                {
                                    self.BTdata.append(BTData(json:item))
                                }

                                self.collectionView1!.reloadData()
                            })
                        }
                    }
                    else
                    {
                        let message = json["message"] as? String

                        print(message)

                        let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)

                        // add an action (button)
                        ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                        // show the alert
                        self.presentViewController(ServerAlert, animated: true, completion: nil)
                    }
                }
            }
        })

        dataTask.resume()
    }

       func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
          return BTdata.count

    }


    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {

            let cell: collview1 = collectionView.dequeueReusableCellWithReuseIdentifier("Cell1", forIndexPath: indexPath) as! collview1
            cell.lblCellA.text = BTdata[indexPath.row].BTNames

            cell.imgCellA.image = UIImage(named: tableImages[indexPath.row])


            return cell


    }




      collection view cell space and size
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {


            return CGSizeMake((self.view.frame.size.width/4) - 10, (self.view.frame.size.width/4) - 15);

    }



}
导入UIKit
类HomeViewController:UIViewController、UICollectionViewDataSource、UICollectionViewDelegate{
@IBOutlet弱var CollectionView 1:UICollectionView!
var BTdata=[BTdata]()
重写func viewDidLoad()
{
super.viewDidLoad()
ListBusinessTypes()
}
//来自业务类型Api的值
func ListBusinessTypes()
{
让token=NSUserDefaults.standardUserDefaults().valueForKey(“访问令牌”)作为!字符串
let headers=[“x-access-token”:token]
let request=NSMutableURLRequest(URL:NSURL(字符串:“某些URL”)!,
cachePolicy:.UseProtocolCachePolicy,
timeoutInterval:10.0)
request.HTTPMethod=“GET”
request.allHTTPHeaderFields=标题
let session=NSURLSession.sharedSession()
让dataTask=session.dataTaskWithRequest(请求,completionHandler:{(数据,响应,错误)->中的Void
如果(错误!=nil)
{
打印(错误)
让ErrorAlert=UIAlertController(标题:“错误”,消息:“internet连接或服务器出现问题,请稍后再试”,首选样式:UIAlertControllerStyle.Alert)
//添加操作(按钮)
ErrorAlert.addAction(UIAlertAction(标题:“确定”,样式:UIAlertActionStyle.Default,处理程序:nil))
//显示警报
self.presentViewController(ErrorAlert,动画:true,完成:nil)
}
其他的
{
如果让json=(尝试?NSJSONSerialization.JSONObjectWithData(data!,选项:[]))作为字典
{
将success=json[“success”]设为?Int
如果(成功==1)
{
如果让typeValues=json[“数据”]as?[NSDictionary]
{
dispatch\u async(dispatch\u get\u main\u queue(){
对于typeValues中的项
{
self.BTdata.append(BTdata(json:item))
}
self.collectionView1!.reloadData()
})
}
}
其他的
{
让message=json[“message”]作为字符串
打印(信息)
让ServerAlert=UIAlertController(标题:“错误”,消息:消息,首选样式:UIAlertControllerStyle.Alert)
//添加操作(按钮)
addAction(UIAlertAction(标题:“确定”,样式:UIAlertActionStyle.Default,处理程序:nil))
//显示警报
self.presentViewController(ServerAlert,动画:true,完成:nil)
}
}
}
})
dataTask.resume()
}
func collectionView(collectionView:UICollectionView,numberOfItemsInSection:Int)->Int
{
返回BTdata.count
}
func collectionView(collectionView:UICollectionView,cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell
{
让cell:collview1=collectionView.dequeueReusableCellWithReuseIdentifier(“Cell1”,forIndexPath:indexPath)作为!collview1
cell.lblCellA.text=BTdata[indexath.row].BTNames
cell.imgCellA.image=UIImage(名称:tableImages[indexPath.row])
返回单元
}
集合视图单元格空间和大小
func collectionView(collectionView:UICollectionView,布局collectionViewLayout:UICollectionViewLayout,SizeFormiteIndeXPath indexPath:NSIndexPath)->CGSize
{
返回CGSizeMake((self.view.frame.size.width/4)-10,(self.view.frame.size.width/4)-15);
}
}

首先不要返回
BTdata。如果大于8,则计数

return BTdata.count>8 ?  8 : BTdata.count;
接下来,在UI编辑器中添加另一种类型的单元格,给它一个名称(例如
SeeMore
),并修改集合视图项处理程序,以便它为最后一行返回适当的单元格:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
  if indexPath.row==7 {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("SeeMore", forIndexPath: indexPath)
    return cell       
  } else {
    let cell: collview1 = collectionView.dequeueReusableCellWithReuseIdentifier("Cell1", forIndexPath: indexPath) as! collview1
    cell.lblCellA.text = BTdata[indexPath.row].BTNames
    cell.imgCellA.image = UIImage(named: tableImages[indexPath.row])
    return cell
  }
}

并在
collectionView(collectionView:UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeFormiteIndeXPath indexPath:NSIndexPath)中相应地返回该单元格的适当大小->CGSize
方法。

返回BTdata.count>8?BTdata.count;
这一行要求我在可选值之后添加逗号?因此,我需要创建另一个cell.xib以查看更多信息。我需要在if条件下调用该单元格。我是指if indexath.rpw==7。我说得对吗?是的,这是我的建议。我会实现它并让你知道!!Yo如果
BTData
中正好有8个项目,则ur
cellForItemAtIndexPath
逻辑是错误的。