【发布时间】:2015-06-11 10:31:51
【问题描述】:
我正在尝试在 iOS 上创建一个 UI 元素,它可以扩展或收缩以适应动态的、通常是多行的文本。我需要在看起来很像消息气泡的文本下方放置一个图像。但是,我在整个 UI 中只需要其中一个,因此表格视图似乎有点过头了——除非有合理的必要性。
我已尝试为此目的使用 UILabel,但它似乎对背景图像的支持非常有限。我只能让它平铺图像,这不是我想要的。
似乎 UIButton 是最简单的构造,应该可以合理地完成我的要求,但我无法让它工作。这是一个在其他方面为空的单一视图应用程序中的代码提炼形式。
- (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)]];
}
这是我运行应用程序时的样子:
显然,我正在寻找的是用于展开以包含其内容的按钮。所以即使最初的渲染是错误的,但是当我稍后动态更改文本时,我还需要正确调整它的大小。
我怎样才能创建这个?我需要在代码中看到答案,因为我还是 iOS 开发的新手。
【问题讨论】:
标签: ios objective-c cocoa-touch uibutton