Created
May 2, 2017 21:45
-
-
Save rcdilorenzo/ba1440d3b4dd00d9eac2c5fca9943dec to your computer and use it in GitHub Desktop.
How to display dynamic length strings in a scrollable popover on iOS with perfect padding ππ»π₯
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Requires a property like the following | |
// @property (nonatomic, strong) UIPopoverController *textPopover; | |
- (void)displayPopoverForText:(NSString *)text inView:(UIView *)view presentingRect:(CGRect)rect maxSize:(CGSize)maxSize { | |
UIViewController *controller = [UIViewController new]; | |
UITextView *textView = [UITextView new]; | |
textView.text = text; | |
textView.editable = NO; | |
textView.backgroundColor = [UIColor clearColor]; | |
textView.textColor = [UIColor blackColor]; | |
textView.textContainerInset = UIEdgeInsetsMake(8, 8, 8, 8); | |
textView.scrollIndicatorInsets = textView.textContainerInset; | |
textView.font = [UIFont systemFontOfSize:[UIFont labelFontSize]]; | |
CGRect boundingRect = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | |
attributes:@{NSFontAttributeName: textView.font} context:nil]; | |
CGSize size = CGSizeMake( | |
MIN(ceil(boundingRect.size.width), maxSize.width - 30) + 30, | |
MIN(ceil(boundingRect.size.height), maxSize.height - 20) + 20 | |
); | |
controller.view.frame = textView.frame = CGRectMake(0, 0, size.width, size.height); | |
textView.textAlignment = [textView.text containsString:@"\n"] ? NSTextAlignmentLeft : NSTextAlignmentCenter; | |
[controller.view addSubview:textView]; | |
controller.preferredContentSize = controller.view.frame.size; | |
self.textPopover = [[UIPopoverController alloc] initWithContentViewController:controller]; | |
[self.textPopover presentPopoverFromRect:rect inView:view | |
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; | |
} | |
// Example Usage: | |
// [self displayPopoverForText:text inView:tableView presentingRect:cell.frame maxSize:CGSizeMake(400, 400)]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment