ios 将标签文本设为链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8724238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:08:32  来源:igfitidea点击:

To make label text as link

ios

提问by Krunal

I have used "Register yourself" as text. I want to make it as link. And by clicking on that link, it should open Register.xib.

我使用了“注册自己”作为文本。我想把它作为链接。通过单击该链接,它应该会打开Register.xib.

How can I get this link??

我怎样才能得到这个链接??

回答by Michael Dautermann

Kareem is right. Create a UIButton object, set it's type to "Custom" and then you can give it a title. Connect the action to a method which pushes or presents your Register view controller and you will be all set.

卡里姆是对的。创建一个 UIButton 对象,将它的类型设置为“自定义”,然后你可以给它一个标题。将操作连接到推送或呈现您的注册视图控制器的方法,您将全部设置。

You'll probably want to give some indication to the user that the text is a clickable link. Either set the color of the text to blue. Another, completely separate option, is to use a NSAttributedString(which has an underline attribute) to indicate to the user that the text is clickable. That requires an Open Source replacement for UITextView(which you can learn more about from this related question).

您可能希望向用户表明该文本是一个可点击的链接。要么将文本的颜色设置为蓝色。另一个完全独立的选项是使用 a NSAttributedString(具有下划线属性)向用户指示该文本是可点击的。这需要UITextView 的开源替代品(您可以从这个相关问题中了解更多信息)。

回答by iTrained

I think by below you will get what you want...

我想在下面你会得到你想要的......

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{   
    NSSet *allTouches = [event allTouches];
    if ([allTouches count] == 1)
    {
        UITouch *touch = (UITouch *)[allTouches anyObject];
        CGPoint touchPoint = [touch locationInView:self];

        // Convert to coordinate system of current view
        touchPoint.y -= self.bounds.size.height;
        touchPoint.y *= -1;

        CGPathRef statusPath = CTFrameGetPath(statusCTFrame);
        NSString *touchedInterStr = nil;
        if (CGPathContainsPoint(statusPath, NULL, touchPoint, FALSE))
        {
            touchedInterStr = [self getInteractiveStringInFrame:statusCTFrameatPosition:touchPoint];
        }
        else
        {
            return ;
        }
    }
}

回答by Alfie Hanssen

There's a middle ground that's worth mentioning. Using UIButtonwith UIButtonTypeCustomhas some shortcomings, namely that you have limited control over the text styling (e.g. you cannot make it right or left aligned, it will always be centered).

有一个中间立场值得一提。使用UIButtonwithUIButtonTypeCustom有一些缺点,即您对文本样式的控制有限(例如,您无法使其右对齐或左对齐,它将始终居中)。

Using NSAttributedStringcan be overkill, and tough to implement if you're unfamiliar with NSAttributedString, CoreText etc.

NSAttributedString如果您不熟悉NSAttributedString、CoreText 等,则使用可能会矫枉过正,并且难以实施。

A solution I've used is a simple subclass of UIControlwhich allows more customization than subclassing UIButtonand less hassle than NSAttributedStringet al. The UIControlapproach is only appropriate if the entire string will be a "link".

我使用的一个解决方案是一个简单的子类,UIControl它允许比子类化更多的定制UIButton和比NSAttributedString等人更少的麻烦。该UIControl方法仅适用于整个字符串都是“链接”的情况。

You would do something like this in your UIControlsubclass:

你会在你的UIControl子类中做这样的事情:

  • Add a UILabelsubview in the init method
  • Configure the UILabelwith your desired backgroundColor, textColor, textAlignmentetc, including changes to the UILabellayer if you want the background to appear like Twitter's in-tweet links in their iOS App
  • Override the setHighlighted:method to customize the look and feel changes on touch/tracking
  • Add @propertysetters in the .hfile so the owning class can set the state
  • UILabel在init方法中添加子视图
  • 配置UILabel成你想要的backgroundColortextColortextAlignment等,包括更改UILabel,如果你希望背景出现像Twitter在其iOS应用鸣叫链接层
  • 重写setHighlighted:方法以自定义触摸/跟​​踪的外观和感觉更改
  • @property.h文件中添加设置器,以便拥有的类可以设置状态

回答by Tejinder

Take a button and set title of the button which you want to set as hyperlink Text. You can choose default and custom button type button in iOS 7 and iOS 8, but for below iOS 7 you have to take button type custom only. You can change colour of the text to highlight text for UI and than add whatever action you want to add on that button click. It will work like charm, good luck.

取一个按钮并设置要设置为超链接文本的按钮的标题。您可以在 iOS 7 和 iOS 8 中选择默认和自定义按钮类型按钮,但对于低于 iOS 7 的您只能选择自定义按钮类型。您可以更改文本的颜色以突出显示 UI 的文本,然后添加您想在该按钮单击时添加的任何操作。它会像魅力一样工作,祝你好运。

回答by halbano

Take a look to TTTAttributedLabel. Is really simple to configure links, phones, etc.

看看TTTAttributedLabel。配置链接、电话等非常简单。

回答by huubby

First, construct the attributed string and save the range of the interactive text and the text itself.

首先,构造属性字符串并保存交互文本的范围和文本本身。

Then, draw the attributed string with CoreText Framework, keep the CTFrameRef.

然后,用 CoreText Framework 绘制属性字符串,保留 CTFrameRef。

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, bounds);

CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CFRelease(framesetter);

CTFrameDraw(frame, context);
//CFRelease(frame);

CGPathRelease(path);

The last, override the [view touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event] like this:

最后,像这样覆盖 [view touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event]:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{   
    NSSet *allTouches = [event allTouches];
    if ([allTouches count] == 1) {
       UITouch *touch = (UITouch *)[allTouches anyObject];
       CGPoint touchPoint = [touch locationInView:self];

       // Convert to coordinate system of current view
       touchPoint.y -= self.bounds.size.height;
       touchPoint.y *= -1;

       CGPathRef statusPath = CTFrameGetPath(statusCTFrame);
       NSString *touchedInterStr = nil;
       if (CGPathContainsPoint(statusPath, NULL, touchPoint, FALSE)) {
          touchedInterStr = [self getInteractiveStringInFrame:statusCTFrame atPosition:touchPoint];
       } else {
          return ;
       }
   }
}

- (NSString *)getInteractiveStringInFrame:(CTFrameRef)frame atPosition:(CGPoint)point
{
    CGPathRef path = CTFrameGetPath(frame);
    CGRect rect;
    CGPathIsRect(path, &rect);

    // Convert point into rect of current frame, to accurately perform hit testing on CTLine
    CGPoint pointInsideRect = point;
    pointInsideRect.x = point.x - rect.origin.x;

    CFArrayRef lines = CTFrameGetLines(statusCTFrame);
    CFIndex count = CFArrayGetCount(lines);
    CGFloat curUpBound = rect.origin.y + rect.size.height;
    CFIndex touchedIndex = -1;
    for (CFIndex pos = 0; pos < count; pos++) {
        CTLineRef curLine = CFArrayGetValueAtIndex(lines, pos);
        CGFloat ascent, descent, leading;
        CTLineGetTypographicBounds(curLine, &ascent, &descent, &leading);
        CGFloat curHeight = ascent + descent + leading;
        if (pointInsideRect.y >= curUpBound-curHeight && pointInsideRect.y <= curUpBound){
            touchedIndex = CTLineGetStringIndexForPosition(curLine, pointInsideRect);   // Hit testing
            break;
        }
        curUpBound -= curHeight;
    }
    if (touchedIndex == -1)
        return nil;

    NSEnumerator *enumerator = [interactiveStrs objectEnumerator];
    InteractiveString *curString;
    while ((curString = (InteractiveString *)[enumerator nextObject])) {
        if (NSLocationInRange(touchedIndex, curString.range)) {
            return curString.content;
        }
    }

    return nil;
}

You get the interactive text in touchesEnded, then you could do anything you want, like trigger a delegate method.

您可以在 touchesEnded 中获得交互式文本,然后您可以做任何您想做的事情,例如触发委托方法。

PS: this is the old-fashion solution, I heard that iOS5 had provided something like an enhanced UIWebView to implement the requirements, maybe you could check the apple sdk document library.

PS:这是老式的方案,听说iOS5已经提供了增强UIWebView之类的东西来实现需求,也许你可以查看apple sdk文档库。