【问题标题】:How can I create a custom UIActivity in iOS?如何在 iOS 中创建自定义 UIActivity?
【发布时间】:2012-09-27 19:02:18
【问题描述】:

如何在 iOS 中创建自定义 UIActivity?

我想要这样做的原因是在我的一个应用程序中添加一个评论应用程序按钮,该按钮将用户带到 App Store 的评论部分。如何创建这样的自定义UIActivity?

【问题讨论】:

    标签: ios objective-c uiactivityviewcontroller uiactivity


    【解决方案1】:

    首先,创建文件。我选择命名我的 ActivityViewCustomActivity

    使 ActivityViewCustomActivity.h 看起来像这样:

    #import <UIKit/UIKit.h>
    
    @interface ActivityViewCustomActivity : UIActivity
    
    @end
    

    使 ActivityViewCustomActivity.m 看起来像这样:

    #import "ActivityViewCustomActivity.h"
    
    @implementation ActivityViewCustomActivity
    
    - (NSString *)activityType
    {
        return @"yourappname.Review.App";
    }
    
    - (NSString *)activityTitle
    {
        return @"Review App";
    }
    
    - (UIImage *)activityImage
    {  
        // Note: These images need to have a transparent background and I recommend these sizes:
        // iPadShare@2x should be 126 px, iPadShare should be 53 px, iPhoneShare@2x should be 100 
        // px, and iPhoneShare should be 50 px. I found these sizes to work for what I was making.
    
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            return [UIImage imageNamed:@"iPadShare.png"];
        }
        else
        {
            return [UIImage imageNamed:@"iPhoneShare.png"];
        }
    }
    
    - (BOOL)canPerformWithActivityItems:(NSArray *)activityItems
    {
        NSLog(@"%s", __FUNCTION__);
        return YES;
    }
    
    - (void)prepareWithActivityItems:(NSArray *)activityItems
    {
        NSLog(@"%s",__FUNCTION__);
    }
    
    - (UIViewController *)activityViewController
    {
        NSLog(@"%s",__FUNCTION__);
        return nil;
    }
    
    - (void)performActivity
    {   
        // This is where you can do anything you want, and is the whole reason for creating a custom 
        // UIActivity
    
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=yourappid"]];
        [self activityDidFinish:YES];
    }
    
    @end
    

    这是我的图像的样子: 这是我制作的 .PSD: -- 删除了恶意链接 -- 这是原始的 250 px .p​​ng http://i.imgur.com/pGWVj.png

    现在在您的视图控制器中执行以下操作:

    #import "ActivityViewCustomActivity.h"
    

    现在无论您想在哪里显示您的UIActivityViewController:

       NSString *textItem = @"Check out the yourAppNameHere app: itunes http link to your app here";
       UIImage *imageToShare = [UIImage imageNamed:@"anyImage.png"];
    
       NSArray *items = [NSArray arrayWithObjects:textItem,imageToShare,nil];
    
       ActivityViewCustomActivity *aVCA = [[ActivityViewCustomActivity alloc]init];
    
       UIActivityViewController *activityVC =
       [[UIActivityViewController alloc] initWithActivityItems:items
                                                      applicationActivities:[NSArray arrayWithObject:aVCA]];
    
       activityVC.excludedActivityTypes = @[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeSaveToCameraRoll];
    
       activityVC.completionHandler = ^(NSString *activityType, BOOL completed)
       {
            NSLog(@"ActivityType: %@", activityType);
            NSLog(@"Completed: %i", completed);
       };
    
       if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
       {
          self.popoverController = [[UIPopoverController alloc] initWithContentViewController:activityVC];
    
          CGRect rect = [[UIScreen mainScreen] bounds];
    
          [self.popoverController
                         presentPopoverFromRect:rect inView:self.view
                         permittedArrowDirections:0
                         animated:YES];
       }
       else
       {
           [self presentViewController:activityVC animated:YES completion:nil];
       }
    

    【讨论】:

    • 根据 iPhone 和 iPod touch 的 Apple 手册,图像不应大于 43 x 43 点(对于配备 Retina 显示屏的设备,这相当于 86 x 86 像素。)对于 iPad,图像应为不大于 55 x 55 点(对于配备 Retina 显示屏的 iPad,这相当于 110 x 110 像素。)
    • Apple 手册并不适用于所有情况。我选择的图像尺寸是经过反复试验,可以完美地满足我的需要。
    • 你能重新上传你的文件吗?它们似乎不再可用。
    • @DrMickeyLauer 我在这里重新上传了 .PSD 文件:datafilehost.com/download-a67ca6f3.html
    • iOS 7 中推荐的图像尺寸发生了变化 - 请参阅 UIActivity 的文档。对于 iPhone 和 iPod touch,iOS 7 上的图像应为 60 x 60 点。对于早期版本:不大于 43 x 43 点。对于 iPad,图像应为 76 x 76 点;在早期版本上:不大于 60 x 60 点。在配备 Retina 显示屏的设备上,每个方向的像素数都翻倍。
    【解决方案2】:

    这是我的 Swift 版本 - 我需要多个自定义操作,所以我创建了这个类。不需要代表或协议。

    1.添加自定义类

    class ActivityViewCustomActivity: UIActivity {
    
        var customActivityType = ""
        var activityName = ""
        var activityImageName = ""
        var customActionWhenTapped:( (Void)-> Void)!
    
        init(title: String, imageName:String, performAction: (() -> ()) ) {
            self.activityName = title
            self.activityImageName = imageName
            self.customActivityType = "Action \(title)"
            self.customActionWhenTapped = performAction
            super.init()
        }
    
        override func activityType() -> String? {
            return customActivityType
        }
    
        override func activityTitle() -> String? {
            return activityName
        }
    
        override func activityImage() -> UIImage? {
            return UIImage(named: activityImageName)
        }
    
        override func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool {
            return true
        }
    
        override func prepareWithActivityItems(activityItems: [AnyObject]) {
            // nothing to prepare
        }
    
        override func activityViewController() -> UIViewController? {
            return nil
        }
    
        override func performActivity() {
            customActionWhenTapped()
        }
    }
    

    2 在您的视图控制器中使用

    我已将它附加到 UIBarButtonItem,它调用以下内容

    @IBAction func actionButtonPressed(sender: UIBarButtonItem) {
    
        var sharingItems = [AnyObject]() // nothing to share...
    
        let myCustomActivity = ActivityViewCustomActivity(title: "Mark Selected", imageName: "removePin") {
            println("Do something")
        }
    
        let anotherCustomActivity = ActivityViewCustomActivity(title: "Reset All", imageName: "reload") {
            println("Do something else")
        }
    
        let activityViewController = UIActivityViewController(activityItems:sharingItems, applicationActivities:[myCustomActivity, anotherCustomActivity])
    
        activityViewController.excludedActivityTypes = [UIActivityTypeMail, UIActivityTypeAirDrop, UIActivityTypeMessage, UIActivityTypeAssignToContact, UIActivityTypePostToFacebook, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeSaveToCameraRoll]
    
        activityViewController.popoverPresentationController?.barButtonItem = sender
    
        self.presentViewController(activityViewController, animated: true, completion: nil)
    }
    

    【讨论】:

    • 很遗憾苹果默认没有这个功能。
    【解决方案3】:

    这是一个使用 UIActivity 的 -activityViewController 方法建立电子邮件编辑器界面的示例。这显示了如何为您选择的任何目的放置 UIKit 视图控制器或您自己的自定义视图控制器。它取代了 -performActivity 方法。

    #import <MessageUI/MessageUI.h>
    #import <UIKit/UIKit.h>
    
    @interface EPSuggestionsActivity : UIActivity <MFMailComposeViewControllerDelegate>
    
    @end
    
    @implementation EPSuggestionsActivity
    
    ....
    
    - (UIViewController *)activityViewController{
    
        MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
        picker.mailComposeDelegate = self;
    
        NSString *emailAddress = @"developer@apple.com";
        NSArray *toRecipients = @[emailAddress];
        [picker setToRecipients:toRecipients];
        [picker setSubject:@"Suggestions"];
    
        return picker;
    }
    
    #pragma mark - MFMailComposeViewControllerDelegate Method
    
    - (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error  {
    
        [self activityDidFinish:YES];   //  Forces the activityViewController to be dismissed
    }
    
    @end
    

    请注意,在用户关闭电子邮件界面后,邮件编写器委托会调用 -activityDidFinish。这是使 UIActivityViewController 界面消失所必需的。如果您编写自己的 viewController,它将需要一个在完成时调用的委托方法,并且您必须将 UIActivity 的子类设为委托。

    【讨论】:

      【解决方案4】:

      我的 Swift 3 基于 DogCoffee 的实现:

      class ActivityViewCustomActivity: UIActivity {
      
          // MARK: Properties
      
          var customActivityType: UIActivityType
          var activityName: String
          var activityImageName: String
          var customActionWhenTapped: () -> Void
      
      
          // MARK: Initializer
      
          init(title: String, imageName: String, performAction: @escaping () -> Void) {
              self.activityName = title
              self.activityImageName = imageName
              self.customActivityType = UIActivityType(rawValue: "Action \(title)")
              self.customActionWhenTapped = performAction
              super.init()
          }
      
      
      
          // MARK: Overrides
      
          override var activityType: UIActivityType? {
              return customActivityType
          }
      
      
      
          override var activityTitle: String? {
              return activityName
          }
      
      
      
          override class var activityCategory: UIActivityCategory {
              return .share
          }
      
      
      
          override var activityImage: UIImage? {
              return UIImage(named: activityImageName)
          }
      
      
      
          override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
              return true
          }
      
      
      
          override func prepare(withActivityItems activityItems: [Any]) {
              // Nothing to prepare
          }
      
      
      
          override func perform() {
              customActionWhenTapped()
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-04-14
        • 1970-01-01
        • 2015-12-02
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多