简体   繁体   中英

How to create a strike through UIButton?

Is it possible to create a button with strike through text without using an image?

I know it's possible to do it to a UILabel

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Your String here"];
[attributeString addAttribute:NSStrikethroughStyleAttributeName
                        value:@2
                        range:NSMakeRange(0, [attributeString length])];

您需要使用setAttributedTitle:forState:传入您创建的属性字符串来设置按钮的标题。

You can try

[button setAttributedTitle:attributeString forState:UIControlStateNormal];
[button setAttributedTitle:attributeString forState:UIControlStateHighlighted]
    let attributes = [NSStrikethroughStyleAttributeName : 1]
    let title = NSAttributedString(string: "YOUR STRING", attributes: attributes)

    button.setAttributedTitle(title, forState: .Normal)

Make a mutable attributed string with Strike Through Attribute and set this attributed string to button's attributed text. Used attributeString code snippet from above @grabury question.

UIButton *button = [UIButton alloc] init];
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Your Text Here"];
    [attributeString addAttribute:NSStrikethroughStyleAttributeName
                            value:@2
                            range:NSMakeRange(0, [attributeString length])];
button.titleLabel.attributedText = attributeString;

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM