Skip to content

Instantly share code, notes, and snippets.

@theoknock
Created September 28, 2022 20:57
Show Gist options
  • Save theoknock/3eb2dd5f031760611dc2123b182084df to your computer and use it in GitHub Desktop.
Save theoknock/3eb2dd5f031760611dc2123b182084df to your computer and use it in GitHub Desktop.
UITextView logging
// Adds log entries to a UITextView
typedef typeof(NSString *) LogEntry;
typedef typeof(NSMutableAttributedString *) LogEntryComposition;
typedef const typeof(LogEntryComposition * restrict) LogEntryCompositionPtr;
typedef typeof(void(^)(LogEntry)) LogEngine;
static void (^(^log_engine)(UITextView *))(LogEntry) = ^ (UITextView * text_view) {
__block LogEntryComposition entry_composition = [[NSMutableAttributedString alloc] init];
return ^ (LogEntry entry) {
dispatch_async(dispatch_get_main_queue(), ^{
NSAttributedString * attributed_entry = [[NSAttributedString alloc] initWithString:entry attributes:^ NSDictionary * (void) {
NSMutableParagraphStyle *leftAlignedParagraphStyle = [[NSMutableParagraphStyle alloc] init];
leftAlignedParagraphStyle.alignment = NSTextAlignmentLeft;
return @{NSForegroundColorAttributeName: [UIColor colorWithRed:0.0 green:0.87 blue:0.19 alpha:1.0],
NSFontAttributeName: [UIFont systemFontOfSize:11.0 weight:UIFontWeightMedium],
NSParagraphStyleAttributeName: leftAlignedParagraphStyle};
}()];
[entry_composition appendAttributedString:attributed_entry];
[text_view setAttributedText:entry_composition];
});
};
};
// Declare a globally scoped variable for use in multiple contexts
static LogEngine textViewLogger;
// Pass a reference to a text view...
textViewLogger = log_engine(self.logTextView);
// Pass an NSString to append a log entry to the existing log
textViewLogger([NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment