LSCategories 1.8.1

LSCategories 1.8.1

测试已测试
Lang语言 Obj-CObjective C
许可证 MIT
发行最后发布2022年9月

Leszek SLeszek S维护。



  • 作者
  • Leszek S

LSCategories

LSCategories是一个包含有用的Foundation和UIKit分类的集合,旨在简化一些常见操作并加快开发过程。它是用Objective-C实现的,但也可以轻松集成并在Swift项目中使用。

安装

要将LSCategories集成到您的Xcode项目中,您可以使用CocoaPods依赖管理器。在您的Podfile中添加以下行:

pod 'LSCategories'

功能

以下列出了使用LSCategories可以轻松完成的一些事情。

从NSString或NSData中使用单行代码创建各种类型的散列和校验和

NSString *sha1 = [@"Test string" lsSHA1];
NSString *sha224 = [@"Test string" lsSHA224];
NSString *sha256 = [@"Test string" lsSHA256];
NSString *sha384 = [@"Test string" lsSHA384];
NSString *sha512 = [@"Test string" lsSHA512];
NSString *md2 = [@"Test string" lsMD2];
NSString *md4 = [@"Test string" lsMD4];
NSString *md5 = [@"Test string" lsMD5];
uint32_t crc32 = [@"Test string" lsCRC32];
uint32_t adler32 = [@"Test string" lsAdler32];

轻松地将图像放入字符串中

NSAttributedString *withPrefix = [@"text" lsAttributedStringWithPrefixImage:[UIImage imageNamed:@"image.png"]];
NSAttributedString *withSuffix = [@"text" lsAttributedStringWithSuffixImage:[UIImage imageNamed:@"image.png"]];
NSAttributedString *withImageInside = [@"text with <image> inline image" lsAttributedStringByReplacingOccurrenceOfString:@"<image>" withImage:[UIImage imageNamed:@"image.png"] verticalOffset:0];

使用XOR或ROT13混淆NSData或NSString,并从不需要的字符中过滤字符串

NSData *data = [@"Some data to xor" lsDataUTF8];
NSData *key = [@"key" lsDataUTF8];
NSData *xoredData = [data lsDataXORedWithKey:key];
NSString *rot13 = [@"Some string" lsROT13String];
NSString *lettersOnly = [test lsStringByRemovingNonLetters];
NSString *numbersOnly = [test lsStringByRemovingNonNumeric];
NSString *numbersAndLettersOnly = [test lsStringByRemovingNonAlphanumeric];
NSString *customFilter = [test lsStringByRemovingCharactersNotInString:@"0123456789+- "];

使用单行代码将NSData保存到或从文档或缓存文件夹中读取

[someData lsSaveToDirectory:NSDocumentDirectory fileName:@"data.bin" useExcludeFromBackup:NO];
NSData *data = [NSData lsReadDataFromDirectory:NSDocumentDirectory fileName:@"data.bin"];
NSArray *directoryContent = [NSData lsContentOfDirectory:NSDocumentDirectory];
[NSData lsCleanDirectory:NSDocumentDirectory];

轻松地对NSDate执行各种常见操作

NSDate *date = [NSDate lsDateWithStringWithISO8601:@"2017-02-03T00:00:00+01:00"];
NSDate *startOfDay = [date lsBeginningOfDay];
NSDate *startOfMonth = [date lsBeginningOfMonth];
NSDate *startOfYear = [date lsBeginningOfYear];
NSDate *endOfDay = [date lsEndOfDay];
NSDate *endOfMonth = [date lsEndOfMonth];
NSDate *endOfYear = [date lsEndOfYear];
NSDate *threeDaysLater = [date lsDateByAddingDays:3];
NSDate *twoMonthsLater = [date lsDateByAddingMonths:2];
NSDate *oneYearEarlier = [date lsDateByAddingYears:-1];
NSInteger year = [date lsYear];
NSInteger month = [date lsMonth];
NSInteger day = [date lsDay];
NSInteger daysDifference = [date lsDaysDifferenceFromDate:startOfYear];
NSInteger monthsDifference = [date lsMonthsDifferenceFromDate:startOfYear];
NSString *isoDateString = [date lsStringWithISO8601];
NSString *shortDateString = [date lsStringWithShortDate];
NSString *mediumDateTimeString = [date lsStringWithMediumDateTime];
NSString *longTimeString = [date lsStringWithLongTime];
BOOL isToday = [date lsIsToday];
BOOL isTomorrow = [date lsIsTomorow];
BOOL isYesterday = [date lsIsYesterday];
BOOL isEarlier = [date lsIsEarlierThanDate:endOfMonth];
BOOL isLater = [date lsIsLaterThanDate:endOfMonth];
BOOL isInBetween = [date lsIsInBetweenStartDate:startOfMonth endDate:endOfMonth];

对UIColor执行各种常见操作

UIColor *color = [UIColor lsColorWithHexString:@"#FF0000"];
UIColor *otherColor = [UIColor lsColorWithRgba:0xFF00FF33];
UIColor *randomColor = [UIColor lsRandomColor];
UIColor *inverted = [randomColor lsInvertedColor];
NSString *hexString = [inverted lsRgbaHexString];
uint32_t rgba = [randomColor lsRgba];
CGFloat hue = [color lsHue];
CGFloat saturation = [color lsSaturation];
CGFloat brightness = [color lsBrightness];

使用给定名称的初始字母生成带有颜色、渐变、三角形、椭圆、文本和头像占位符图像的UIImages

UIImage *red = [UIImage lsImageWithColor:[UIColor redColor] size:CGSizeMake(10, 10)];
UIImage *gradient = [UIImage lsGradientImageWithSize:CGSizeMake(100, 100) startColor:[UIColor redColor] endColor:[UIColor greenColor] startPoint:CGPointMake(0, 0) endPoint:CGPointMake(0, 1)];
UIImage *triangle = [UIImage lsTriangleImageWithColor:[UIColor blueColor] size:CGSizeMake(40, 30)];
UIImage *ellipse = [UIImage lsEllipseImageWithColor:[UIColor blueColor] size:CGSizeMake(70, 30)];
UIImage *imageWithText = [UIImage lsImageWithText:@"HELLO WORLD!" textColor:[UIColor whiteColor] backgroundColor:[UIColor blueColor] font:[UIFont boldSystemFontOfSize:20] size:CGSizeMake(200, 50)];
UIImage *avatar = [UIImage lsInitialsAvatarImageWithText:@"John Doe"];

使用UIBezierPaths从任何形状生成UIImages

UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 200, 100) cornerRadius:20];
UIImage *image = [path lsImageWithStrokeColor:[UIColor blueColor] fillColor:[UIColor greenColor] backgroundColor:[UIColor redColor]];

加载动画GIF或动画PNG文件

UIImage *animatedGif = [UIImage lsAnimatedImageWithAnimatedImageName:@"animated.gif" framesPerSecond:25 bundle:nil];
UIImage *animatedPng = [UIImage lsAnimatedImageWithAnimatedImageName:@"animated.png" framesPerSecond:25 bundle:nil];

在现有的UIImages上执行常见操作

UIImage *image = [UIImage imageNamed:@"image.png"];
UIImage *flippedHorizontally = [image lsImageFlippedHorizontally];
UIImage *flippedVertically = [image lsImageFlippedVertically];
UIImage *rotated = [image lsRotatedImageWithDegrees:45.0];
UIImage *resized = [image lsResizedImageWithSize:CGSizeMake(200, 100)];
UIImage *resizedProportional = [image lsResizedProportionalImageWithMaxSize:CGSizeMake(500, 500)];
UIImage *resizedWithWidth = [image lsResizedProportionalImageWithWidth:500];
UIImage *resizedWithHeight = [image lsResizedProportionalImageWithHeight:500];
UIImage *cropped = [image lsCroppedImageWithRect:CGRectMake(0, 20, 60, 20)];
UIImage *padded = [image lsPaddedImageWithInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
UIImage *inverted = [image lsInvertedImage];
UIImage *masked = [image lsMaskedImageWithMaskImage:mask];
UIImage *merged = [image lsMergedImageWithImage:rotated position:CGPointZero];
UIImage *rounded = [image lsRoundedImageWithCornerRadius:10];
NSData *pngData = [image lsPNG];
NSData *jpegData = [image lsJPEGWithCompressionLevel:0.8];
NSData *jpegDataWithSize = [image lsJPEGWithDesiredMaxSize:2000 allowAboveMax:NO];
NSData *rgbaRawData = [image lsRGBARawData];
UIImage *imageFromRawData = [UIImage lsImageWithRGBARawData:rgbaRawData size:CGSizeMake(20, 30)];
UIColor *averageImageColor = [image lsAverageColor];

异步从JSON获取NSData、NSString或从给定URL获取UIImage

[NSData lsDataFromUrl:[NSURL URLWithString:@"https://google.com"] handler:^(NSData *data, NSError *error) {
    // do something
}];
[NSString lsStringFromUrl:[NSURL URLWithString:@"https://github.com"] handler:^(NSString *string, NSError *error) {
    // do something
}];
[NSDictionary lsDictionaryFromJsonUrl:[NSURL URLWithString:@"https://dummyurl.com/json"] handler:^(NSDictionary *jsonDictionary, NSError *error) {
    // do something
}];
[UIImage lsImageFromUrl:[NSURL URLWithString:@"https://dummyurl.com/image.jpg"] useCache:YES useDiskCache:YES handler:^(UIImage *image, NSError *error) {
    // do something
}];

从HTML标签轻松设置UILabel上的属性文本;也可以使用HTML标签或自定义标签创建属性字符串

self.label.text = @"test <h1>with</h1> <s>some</s> <strong>basic</strong> <em>html</em> <u>tags</u>";
[self.label lsParseBasicHTMLTags];

NSAttributedString *attributedString = [@"Text with <strong>basic</strong> <em>HTML</em>" lsAttributedStringWithDefaultTagStylesheet];

NSAttributedString *withCustomTags = [@"Text with <custom>custom</custom> tag" lsAttributedStringWithTagStylesheet:@{ @"custom" : @{ NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle), NSFontAttributeName : [UIFont systemFontOfSize:20] }}];

仅为UIView的一侧添加边框

[self.someView lsAddBorderOnEdge:UIRectEdgeBottom color:[UIColor blueColor] width:2];
// ...
[self.someView lsRemoveBordersOnEdges];

轻松为视图实现无限旋转

[self.rotatingView lsStartInfiniteRotationWithDuration:2 clockwise:YES];
// ...
[self.rotatingView lsStopInfiniteRotation];

如果您需要加载视图,只需使用标准的旋转加载器来覆盖视图,在加载数据或显示消息时使用

[self.view lsShowActivityIndicator];
// ...
[self.view lsHideActivityIndicator];
// or if you want some customization...
[self.view lsShowActivityIndicatorWithStyle:UIActivityIndicatorViewStyleWhiteLarge color:[UIColor redColor] backgroundColor:[UIColor whiteColor] coverColor:[UIColor yellowColor] text:@"Downloading data"];
// you can also cover the whole screen instead of a single view with a global activity indicator like this
[UIView lsShowSharedActivityIndicator];
// and hide it with
[UIView lsHideSharedActivityIndicator];
// show a toast
[UIView lsShowSharedToastWithText:@"Hello there!"];
// and hide it
[UIView lsHideSharedToast];

在一段时间内更改任何对象的自定义属性(例如,用于动画一些不能以常规方式动画化的东西)

[UIView lsRepeatWithDuration:2 delay:3 framesPerSecond:60 block:^(CGFloat progress) {
    self.label.text = @(progress * 1000).stringValue;
} completionBlock:nil];
// actually for animating incrementing or decrementing a number
// on a UILabel like above you can also use a shortcut
[self.label lsAnimateCounterWithStartValue:10 endValue:1000 duration:2 completionBlock:nil];

通过单行代码限制UITextField的编辑,轻松更改文本填充、占位符颜色和清除按钮的外观

// limit string length in the field
[self.textField lsSetMaxLength:4];
// or limit edition to entering decimal numbers only with specified number of digits before and after decimal point
[self.textField lsSetAllowedDecimalsWithIntegerPart:4 fractionalPart:2];
// or limit characters that can be entered in the field with NSCharacterSet
[self.textField lsSetAllowedCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"abc"]];
// or limit text entry with a regular expression
[self.textField lsSetAllowedRegex:@"^[0-9]{0,4}$"];
// change the color of the clear button...
[self.textField lsSetClearButtonWithColor:[UIColor redColor] mode:UITextFieldViewModeAlways];
// or the image used for clear button
[self.textField lsSetClearButtonWithImage:image mode:UITextFieldViewModeWhileEditing];
// adjust text padding without subclassing
[self.textField lsSetLeftPadding:10];
// set a placeholder text with given color
[self.textField lsSetPlaceholder:@"Placeholder" color:[UIColor redColor]];

使用带有完成块的UINavigationController

[self.navigationController lsPushViewController:vc animated:YES completionBlock:^{
    // do something
}];
[self.navigationController lsPopViewControllerAnimated:YES completionBlock:^{
    // do something
}];

轻松自定义导航栏或标签栏的颜色

[self.navigationController lsSetNavigationBarColor:[UIColor redColor] titleColor:[UIColor whiteColor] buttonsColor:[UIColor yellowColor] borderColor:[UIColor blackColor]];
[self.tabBarController lsSetTabBarColor:[UIColor redColor] itemColor:[[UIColor whiteColor] colorWithAlphaComponent:0.7] selectedItemColor:[UIColor whiteColor] borderColor:[UIColor blackColor]];

在给定块中捕获Objective-c异常。如果您在Swift语言中编程并且需要从Swift代码中捕获Objective-C异常,这非常有用。

NSException *exception = [NSException lsTryCatchWithBlock:^{
    // some code that throws Objective-C exception which cannot be catched from pure Swift code
    // for example something like this below
    [viewController setValue:@"test" forKey:@"nonExistingKey"];
}];

从任何对象发送事件,并通过处理程序订阅它们,或者以简单的方式使用处理程序进行键值观察

[self lsSendEvent:@"DataRefreshedEvent" data:nil];
// ...
[someObject lsSubscribeForEvent:@"DataRefreshedEvent" handler:^(id data) {
    // do something
}];
// ...
[someObject lsObserveValueForKeyPath:@"test" handler:^(NSDictionary * _Nullable change) {
    // do something when test property changed
}];

如果需要确保您正在有效当前日期上工作,从公共在线时间服务器获取当前日期和时间

[NSDate lsDateFromOnlineServerWithHandler:^(NSDate * _Nullable date) {
    // do something with NSDate returned by a time server
}];

启用自动键盘处理,包括自动滚动带文本字段的滚动视图,自动下一个和完成键盘操作(用于切换到下一个文本字段或关闭键盘),以及在调用您的视图控制器中的单行代码时自动隐藏键盘

[self lsEnableAutomaticKeyboardHandling];
// or enable only some of these features for specific views depending on your needs
[self.view lsEnableHideKeyboardOnTap];
[self.textField lsEnableAutomaticNextAndDoneButtonsOnKeyboard];
[self.otherTextField lsEnableAutomaticReturnButtonOnKeyboard];
[self.scrollView lsEnableAutomaticScrollAdjustmentsWhenKeyboardAppear];

使用自动布局视图,轻松在UITableView中为tableHeaderView和tableFooterView自动计算其高度

[self.tableView lsSetAutolayoutTableHeaderView:autolayoutHeaderView];
[self.tableView lsSetAutolayoutTableFooterView:autolayoutFooterView];

当特定条件满足时,将请用户在应用商店进行评分的操作轻松添加到您的应用程序中,以获得您应用用户在应用商店的最佳评分

// in app delegate log app launch...
[[UIApplication sharedApplication] lsLogLaunchForAppRating];
// log some important events in your app...
[[UIApplication sharedApplication] lsLogSignificantEventForAppRating];
// and then ask for rating when user performed desired number of important events and uses the app for specific amount of time
[[UIApplication sharedApplication] lsAskForAppRatingIfReachedMinimumDaysOfUse:5 minimumSignificantEvents:7];

这些只是您可以使用LSCategories做的几件事情。您可以在TestProject中查看其他几个示例。

许可

LSCategories采用MIT许可。请参阅LICENSE.