UICollectionView:ObjC Apple 示例代码到 Swift 转换(找不到成员)

Posted

技术标签:

【中文标题】UICollectionView:ObjC Apple 示例代码到 Swift 转换(找不到成员)【英文标题】:UICollectionView: ObjC Apple sample code to Swift conversion (could not find member) 【发布时间】:2014-07-08 22:00:27 【问题描述】:

我尝试将 Apple 为 UICollectionView (https://developer.apple.com/library/prerelease/ios/samplecode/CircleLayout/Introduction/Intro.html) 提供的示例代码转换为 Swift。

但是,在编写时(视图控制器,第 82 行):self.collectionView.performBatchUpdates(self.collectionView.deleteItemsAtIndexPaths(NSArray(object: tappedCellPath)), completion: nil)

我得到了错误

Could not find member 'performBatchUpdates'

因此,我什至连建筑都达不到。

这是我的完整代码:

AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate 

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool 
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // Override point for customization after application launch.
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()
        return true
    

    func applicationWillResignActive(application: UIApplication) 
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    

    func applicationDidEnterBackground(application: UIApplication) 
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    

    func applicationWillEnterForeground(application: UIApplication) 
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    

    func applicationDidBecomeActive(application: UIApplication) 
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    

    func applicationWillTerminate(application: UIApplication) 
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    



ViewController.swift

import UIKit

let reuseIdentifier = "Cell"

class ViewController: UICollectionViewController 

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) 
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        // Custom initialization
    

    override func viewDidLoad() 
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        cellCount = 20
        var tapRecognizer : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGesture:")
        self.collectionView.addGestureRecognizer(tapRecognizer)
        self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        self.collectionView.reloadData()
        self.collectionView.backgroundColor = UIColor.scrollViewTexturedBackgroundColor()
        // Do any additional setup after loading the view.
    

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

    /*
    // #pragma mark - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 
    
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    */

    // #pragma mark UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView?) -> Int 
        //#warning Incomplete method implementation -- Return the number of sections
        return 0
    


    override func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int 
        //#warning Incomplete method implementation -- Return the number of items in the section
        return cellCount!
    

    override func collectionView(collectionView: UICollectionView?, cellForItemAtIndexPath indexPath: NSIndexPath?) -> UICollectionViewCell? 
        let cell = collectionView?.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell

        // Configure the cell

        return cell
    

    func handleTapGesture(sender: UITapGestureRecognizer) 

        if (sender.state == .Ended) 
            println("tap")
            var initialPinchPoint : CGPoint = sender.locationInView(self.collectionView)
            var tappedCellPath : NSIndexPath = self.collectionView.indexPathForItemAtPoint(initialPinchPoint)

            if (tappedCellPath != nil) 
                cellCount = cellCount!-1
                self.collectionView.performBatchUpdates(self.collectionView.deleteItemsAtIndexPaths(NSArray(object: tappedCellPath)), completion: nil)
             else 
                cellCount = cellCount!+1
                self.collectionView.performBatchUpdates(self.collectionView.insertItemsAtIndexPaths(NSArray(object: tappedCellPath)), completion: nil)
            
        
    

    // pragma mark <UICollectionViewDelegate>

    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    func collectionView(collectionView: UICollectionView?, shouldHighlightItemAtIndexPath indexPath: NSIndexPath?) -> Bool 
    return true
    
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    func collectionView(collectionView: UICollectionView?, shouldSelectItemAtIndexPath indexPath: NSIndexPath?) -> Bool 
    return true
    
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    func collectionView(collectionView: UICollectionView?, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath?) -> Bool 
    return false
    

    func collectionView(collectionView: UICollectionView?, canPerformAction action: String?, forItemAtIndexPath indexPath: NSIndexPath?, withSender sender: AnyObject) -> Bool 
    return false
    

    func collectionView(collectionView: UICollectionView?, performAction action: String?, forItemAtIndexPath indexPath: NSIndexPath?, withSender sender: AnyObject) 

    
    */


Cell.swift

import UIKit

class Cell: UICollectionViewCell 

    init(frame: CGRect) 
        super.init(frame: frame)

        self.contentView.layer.cornerRadius = 35
        self.contentView.layer.borderWidth = 1
        self.contentView.layer.borderColor = UIColor.whiteColor().CGColor
        self.contentView.backgroundColor = UIColor.clearColor()
    


CircleLayout.swift

import UIKit
import QuartzCore

var cellCount : NSInteger?
var center : CGPoint?
var radius : CGFloat?

var deleteIndexPaths : NSMutableArray?
var insertIndexPaths : NSMutableArray?

class CircleLayout: UICollectionViewLayout 
    var centerX : CGFloat?
    var centerY : CGFloat?


    override func prepareLayout() 
        super.prepareLayout()

        var size : CGSize = self.collectionView.frame.size
        cellCount = self.collectionView.numberOfItemsInSection(0)
        center = CGPointMake(size.width/2.0, size.height/2.0)
        centerX = center!.x
        centerY = center!.y
        radius = 300
    

    override func collectionViewContentSize() -> CGSize 
        return self.collectionView.frame.size
    

    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath!) -> UICollectionViewLayoutAttributes! 
        var attributes : UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
        attributes.size = CGSizeMake(70, 70)
        attributes.center = CGPointMake(0,0)
        return attributes
    

    override func layoutAttributesForElementsInRect(rect: CGRect) -> AnyObject[]! 
        var attributes : NSMutableArray = NSMutableArray.array()

        for (var i = 0; i<cellCount!; i++) 
            var indexPath : NSIndexPath = NSIndexPath(forItem: i, inSection: 0)
            attributes.addObject(self.layoutAttributesForItemAtIndexPath(indexPath))
        
        return attributes
    

    override func prepareForCollectionViewUpdates(updateItems: AnyObject[]!) 

        super.prepareForCollectionViewUpdates(updateItems)

        deleteIndexPaths = NSMutableArray.array()
        insertIndexPaths = NSMutableArray.array()

        for update : AnyObject in updateItems
            if (update.updateAction == UICollectionUpdateAction.Delete) 
                deleteIndexPaths!.addObject(update.indexPathBeforeUpdate)
             else if (update.updateAction == UICollectionUpdateAction.Insert) 
                insertIndexPaths!.addObject(update.indexPathAfterUpdate)
            
        
    

    override func finalizeCollectionViewUpdates() 
        deleteIndexPaths = nil
        insertIndexPaths = nil
    

    override func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath!) -> UICollectionViewLayoutAttributes! 

        var attributes : UICollectionViewLayoutAttributes = super.initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath)

        if (insertIndexPaths!.containsObject(itemIndexPath)) 
            if(attributes == false) 
                attributes = self.layoutAttributesForItemAtIndexPath(itemIndexPath)
                attributes.alpha = 0.0
                attributes.center = CGPointMake(center!.x, center!.y)
            
        
        return attributes
    

    override func finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath: NSIndexPath!) -> UICollectionViewLayoutAttributes! 
        var attributes : UICollectionViewLayoutAttributes = super.finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath)

        if (deleteIndexPaths!.containsObject(itemIndexPath)) 
            if(attributes == false) 
                attributes = self.layoutAttributesForItemAtIndexPath(itemIndexPath)
                attributes.alpha = 0.0
                attributes.center = CGPointMake(center!.x, center!.y)
                attributes.transform3D = CATransform3DMakeScale(0.1,0.1,1.0)
            
        
        return attributes

    


【问题讨论】:

请删除所有不相关的代码。说真的 - 没有人会阅读所有这些内容。 1.您是否尝试过将失败的行拆分为几行(带有临时变量)?由于 Swift 编译器的错误,有时它会神奇地提供帮助。 2. 您是否尝试过清理目标并重建?这有时也有帮助。 我不知道问题出在代码的哪一部分。如果我只是发布我认为相关的代码,我可能会错过导致问题的部分。 @radex - 我试过这样做,但这并没有让我走得很远。你能给我举个例子吗? 【参考方案1】:

performBatchUpdates 需要一个块作为它的第一个参数。我相信这会按预期工作:

self.collectionView.performBatchUpdates(
   self.collectionView.deleteItemsAtIndexPaths(NSArray(object: tappedCellPath))
, completion: nil)

【讨论】:

这解决了这个问题!非常感谢——我一定是瞎了眼!

以上是关于UICollectionView:ObjC Apple 示例代码到 Swift 转换(找不到成员)的主要内容,如果未能解决你的问题,请参考以下文章

UICollectionView - 复制 Photos.app 功能

Runtime objc4-779.1 App启动过程中Runtime都干了什么?

iOS中UITableView和UICollectionView的默认空态页

Runtime objc4-779.1 App启动过程中Runtime都干了什么?

UICollectionView 在保持位置上方插入单元格(如 Messages.app)

UICollectionView:像 Safari 选项卡或 App Store 搜索一样分页