且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在 UILabel/UITextView 中添加 UIButton?

更新时间:2023-12-01 19:04:46

@vienvu 删除的答案最接近通过使用 YYText 库.

@vienvu's deleted answer is closest to solve the problem by making use of YYText library.

NSString *text = @"Test adding UIButton #option# inline";
NSMutableAttributedString *method2text = [[NSMutableAttributedString alloc] initWithString:text];
UIFont *font = [UIFont systemFontOfSize:20];
NSMutableAttributedString *attachment = nil;

NSRange range = [[method2text string] rangeOfString:@"#option#"];
if(range.location != NSNotFound) {
    UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    tf.borderStyle = UITextBorderStyleRoundedRect;
    attachment = [NSMutableAttributedString yy_attachmentStringWithContent:tf contentMode:UIViewContentModeBottom attachmentSize:tf.frame.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
    [method2text replaceCharactersInRange:range withString:@""];
    [method2text insertAttributedString:attachment atIndex:range.location];

}

theLabel = [YYLabel new];
theLabel.userInteractionEnabled = YES;
theLabel.numberOfLines = 0;
theLabel.frame = CGRectMake(0, 100, 320, 320);
theLabel.center = self.view.center;
theLabel.attributedText = method2text;
[self.view addSubview:theLabel];

其中 theLabelYYLabel.我发现 YYTextView 无法选择 UI 元素.类似的代码也适用于 UIButton.

where theLabel is a YYLabel. I found that YYTextView cannot select the UI elements. Similar codes are workable for UIButton too.