【问题标题】:Is there a way to implicitly make an button be multi-line?有没有办法隐式地使按钮成为多行?
【发布时间】:2026-02-17 19:00:01
【问题描述】:

我想要一个类似这样的按钮:

ONE
TWO

一个词在另一个词之上。但是,它可能是:

THREE
FOUR

或者任何数字,真的。 NSAttributedStrings 有没有一种方法可以让我在第一个单词之后总是有一个换行符?

【问题讨论】:

    标签: ios objective-c uibutton uilabel nsattributedstring


    【解决方案1】:

    这真的不是关于NSAttributedStringNSString,而是关于按钮本身。您可能会考虑继承 UIButton 并覆盖 setTitle:forState: 以自动将第一个空格替换为 \n

    具体来说,setTitle:forState: 看起来像这样

    - (void)setTitle:(NSString *)title forState:(UIControlState)state {
        NSRange firstSpaceRanger = [title rangeOfString:@" "];
        if (firstSpaceRanger.location != NSNotFound) {
            title = [title stringByReplacingCharactersInRange:firstSpaceRanger withString:@"\n"];
        }
        [super setTitle:title forState:state];
    }
    

    例如,给定one two three,这将产生

    one
    two three
    

    为了使按钮多行,您可以在 UIButton 初始化程序中:

    self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    

    是的,firstSpaceRanger 是故意的。我无法抗拒。

    【讨论】:

      最近更新 更多