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

标签 ios uiviewcontroller swift uicollectionview

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

但是,在编写时(View Controller,第 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

    }

}

最佳答案

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

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

关于ios - UICollectionView:ObjC Apple 示例代码到 Swift 的转换(找不到成员),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24642210/

相关文章:

ios - 横向模式下事件指示器未居中

android - 声学指纹识别背后的原理是什么?

ios - 在 UINavigationController 中包装 UIViewController

iphone - 如何知道 UIViewController View 在后台后何时显示?

ios - 根据文本标注高度

ios - 从 JSON 填充表

ios - 如何使用宽度和字体大小获取字符串高度?

swift - 从 UIView [Swift] 的 URL 获取图像

ios - 如何为firebase编写同步查询调用?

ios - 想要固定方向,但 UIImage 自动旋转