I am trying to create a user interface element in iOS that expands or compresses to fit dynamic, often multi-line text. I need to put an image under the text, which is very similar to a message bubble. However, I only need one of them in my entire user interface, so looking at a table seems unnecessary - if that is not reasonable.
I tried using UILabel for this purpose, but there seems to be very limited support for background images. I can only get it in order to draw an image that I donβt want.
It seems that a UIButton - the most simple design, which should reasonably do what I ask, but I can not make it work. Here's a distilled form of code in another empty application with one view.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
UIImage *image = [[UIImage imageNamed:@"speak_bubble_solid"] resizableImageWithCapInsets:UIEdgeInsetsMake(16, 24, 30, 12)];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setTitle:text forState:UIControlStateNormal];
button.titleLabel.textColor = [UIColor whiteColor];
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.titleLabel.numberOfLines = 0;
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.contentEdgeInsets = UIEdgeInsetsMake(16, 10, 30, 10);
button.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:button];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[button]-|"
options:NSLayoutFormatAlignAllTop
metrics:0
views:NSDictionaryOfVariableBindings(button)]];
}
Here's what it looks like when I launch the application:

Obviously, I'm looking for a button for an extension to contain its contents. Thus, even the initial render is erroneous, but I also need it to be correctly detected when I change the text dynamically later.
How can I create this? I need to see the answer in the code, since I'm still very new to iOS development.
source
share