如何在UILabel的末尾添加更多按钮?

时间:2014-10-08 06:06:22

标签: ios objective-c iphone

我一直在研究这个问题。 我需要在点击位于UILabel文字末尾的按钮时展开并折叠UILabel文字。

认为我已经尝试过了 我已经使用VSWordDetector来检测UILabel哪个单词被点击但是没有给出正确的单词。

1 个答案:

答案 0 :(得分:2)

我建议您使用UIButton而不使用titleLabel.text @"..."@"▼"的可见框架。 因此,例如,您有一个字符串@"Some long long, really long string which couldn't be presented in one line"。然后为UILabel文本取一个子字符串,并在标签右侧放置上述按钮。添加▼-buuton的操作以更新label.text并隐藏按钮。 代码段:

@interface YourClass

@property (strong, nonatomic) UILabel* longStringLabel;
@property (strong, nonatomic) UIButton* moreButton;
@property (strong, nonatomic) NSString* text;

@end

@implementation YourClass

// Some method, where you add subviews, for example viewDidLoad
{
// ...
    self.longStringLabel.frame = CGRectMake(0, 0, 100, 44);
    [self addSubview:self.longStringLabel];

    self.moreButton.frame = CGRectMake(CGRectGetMaxX(self.longStringLabel.frame), 0, 20, 44);
    [self addSubview:self.moreButton];
// ...
}

- (UILabel*)longStringLabel
{
    if (!_longStringLabel)
    {
        _longStringLabel = [UILabel new];
        _longStringLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    }

    return _longStringLabel;
}

- (UIButton*)moreButton
{
    if (!_moreButton)
    {
        _moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _moreButton.titleLabel.text = @"▼";
        [_moreButton addTarget:self action:@selector(moreButtonDidTap:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreButton;
}

- (void)moreButtonDidTap:(UIButton*)sender
{
    self.longStringLabel.frame = [self.text boundingRectWithSize:CGSizeMake(self.longStringLabel.frame.size.width + self.moreButton.frame.size.width, 100)
                                                         options:NSStringDrawingUsesLineFragmentOrigin
                                                      attributes:@{ NSFontAttributeName : self.longStringLabel.font }
                                                         context:nil];
    self.longStringLabel.text = self.text;

    self.moreButton.hidden = YES;
}

@end