119

アプリにクリック可能なラベルを作成して、SafariのWebページに移動したいと思います。また、ユーザーが番号をクリックするだけで電話をかけられるようにしたいですか?

アドバイスありがとうございます

4

10 に答える 10

141

インスペクターでを使用してUITextView、リンク、電話番号などの検出を選択できます。

于 2012-05-21T08:43:40.243 に答える
98

UITextViewの代わりに使用UILabelすると、テキストをハイパーリンクに変換するプロパティがあります。

Objective-C:

yourTextView.editable = NO;
yourTextView.dataDetectorTypes = UIDataDetectorTypeAll;

迅速:

yourTextView.editable = false; 
yourTextView.dataDetectorTypes = UIDataDetectorTypes.All;

これにより、リンクが自動的に検出されます。

詳細については、ドキュメントを参照してください。

于 2012-05-21T18:46:03.697 に答える
29

https://github.com/mattt/TTTAttributedLabel

それは間違いなくあなたが必要なものです。アンダースコアなどの属性をラベルに適用したり、ラベルにさまざまな色を適用したりすることもできます。クリック可能なURLの説明を確認してください。

主に、次のようなことを行います。

NSRange range = [label.text rangeOfString:@"me"];
[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring
于 2012-05-21T08:53:05.310 に答える
12

カスタムUIButtonとsetTextを好きなように作成し、それを使用してメソッドを追加できます。

UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(kLeftMargin, 10, self.view.bounds.size.width - kLeftMargin - kRightMargin, 52)];
[sampleButton setTitle:@"URL Text" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];


[sampleButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton];


-(void)buttonPressed:(id)sender{
  // open url
}
于 2012-05-21T08:44:10.420 に答える
11

これをUITextViewではなくUILabelで処理する場合は、次のようにUILabelサブクラスを作成できます。

class LinkedLabel: UILabel {

fileprivate let layoutManager = NSLayoutManager()
fileprivate let textContainer = NSTextContainer(size: CGSize.zero)
fileprivate var textStorage: NSTextStorage?


override init(frame aRect:CGRect){
    super.init(frame: aRect)
    self.initialize()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.initialize()
}

func initialize(){

    let tap = UITapGestureRecognizer(target: self, action: #selector(LinkedLabel.handleTapOnLabel))
    self.isUserInteractionEnabled = true
    self.addGestureRecognizer(tap)
}

override var attributedText: NSAttributedString?{
    didSet{
        if let _attributedText = attributedText{
            self.textStorage = NSTextStorage(attributedString: _attributedText)

            self.layoutManager.addTextContainer(self.textContainer)
            self.textStorage?.addLayoutManager(self.layoutManager)

            self.textContainer.lineFragmentPadding = 0.0;
            self.textContainer.lineBreakMode = self.lineBreakMode;
            self.textContainer.maximumNumberOfLines = self.numberOfLines;
        }

    }
}

func handleTapOnLabel(tapGesture:UITapGestureRecognizer){

    let locationOfTouchInLabel = tapGesture.location(in: tapGesture.view)
    let labelSize = tapGesture.view?.bounds.size
    let textBoundingBox = self.layoutManager.usedRect(for: self.textContainer)
    let textContainerOffset = CGPoint(x: ((labelSize?.width)! - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: ((labelSize?.height)! - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)

    let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
    let indexOfCharacter = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)


    self.attributedText?.enumerateAttribute(NSLinkAttributeName, in: NSMakeRange(0, (self.attributedText?.length)!), options: NSAttributedString.EnumerationOptions(rawValue: UInt(0)), using:{
        (attrs: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in

        if NSLocationInRange(indexOfCharacter, range){
            if let _attrs = attrs{

                UIApplication.shared.openURL(URL(string: _attrs as! String)!)
            }
        }
    })

}}

このクラスは、この回答のコードを再利用して作成されました。属性付きの文字列を作成するには、この回答を確認してください。そしてここであなたは電話のURLを作る方法を見つけることができます。

于 2016-11-22T16:35:23.540 に答える
7

ラベルテキスト全体ではなく、特定のテキストへの青色のリンクを作成するので、これを使用してください:FRHyperLabel

利用規約にハイパーリンクをスマートに適用する

行うには:

  1. 上記のリンクからダウンロードして、プロジェクトにコピーFRHyperLabel.hFRHyperLabel.mます。

  2. 画像に示すように、をドラッグアンドドロップUILabelしてStoryboardカスタムクラス名を定義しFRHyperLabel、インスペクターを識別します。

ここに画像の説明を入力してください

  1. UILabelをストーリーボードからviewController.hファイルに接続します

@property (weak, nonatomic) IBOutlet FRHyperLabel *label;

  1. 次に、viewController.mファイルに次のコードを追加します。

`NSString * string = @"アップロードすることにより、利用規約に同意します "; NSDictionary * attributes = @ {NSFontAttributeName:[UIFont priorityFontForTextStyle:UIFontTextStyleHeadline]};

_label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
[_label setFont:[_label.font fontWithSize:13.0]];

[_label setLinkForSubstring:@"Terms of Use" withLinkHandler:^(FRHyperLabel *label, NSString *substring){
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];
}];`
  1. そしてそれを実行します。
于 2016-03-04T12:11:09.797 に答える
5

UILabelの代わりにUITextViewを使用すると、テキストをハイパーリンクに変換するプロパティがあります

スウィフトコード:

yourTextView.editable = false
yourTextView.dataDetectorTypes = UIDataDetectorTypes.All
//or
yourTextView.dataDetectorTypes = UIDataDetectorTypes.PhoneNumber
//or
yourTextView.dataDetectorTypes = UIDataDetectorTypes.Link
于 2016-07-04T16:54:33.847 に答える
0
extension UITapGestureRecognizer {

    func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {

        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size: CGSize.zero)
        let textStorage = NSTextStorage(attributedString: label.attributedText!)

        // Configure layoutManager and textStorage
        layoutManager.addTextContainer(textContainer)
        textStorage.addLayoutManager(layoutManager)

        // Configure textContainer
        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = label.lineBreakMode
        textContainer.maximumNumberOfLines = label.numberOfLines
        textContainer.size = label.bounds.size

        // main code
        let locationOfTouchInLabel = self.location(in: label)

        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInLabel, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        let indexOfCharacterRange = NSRange(location: indexOfCharacter, length: 1)
        let indexOfCharacterRect = layoutManager.boundingRect(forGlyphRange: indexOfCharacterRange, in: textContainer)
        let deltaOffsetCharacter = indexOfCharacterRect.origin.x + indexOfCharacterRect.size.width

        if locationOfTouchInLabel.x > deltaOffsetCharacter {
            return false
        } else {
            return NSLocationInRange(indexOfCharacter, targetRange)
        }
    }
}
于 2017-05-31T11:56:47.927 に答える
0

NSMutableAttributedStringを使用しないのはなぜですか?

let attributedString = NSMutableAttributedString(string: "Want to learn iOS? Just visit developer.apple.com!")
        attributedString.addAttribute(.link, value: "https://developer.apple.com", range: NSRange(location: 30, length: 50))

        myView.attributedText = attributedString

あなたはここでより多くの詳細を見つけることができます

于 2019-09-03T19:31:48.783 に答える
-3

UIButtonを使用したSwift4.0の可能なソリューション

     phoneButton = UIButton(frame: CGRect(x: view.frame.width * 0, y: view.frame.height * 0.1, width: view.frame.width * 1, height: view.frame.height * 0.05))
     phoneButton.setTitle("333-333-3333", for: .normal )
     phoneButton.setTitleColor(UIColor(red: 0 / 255, green: 0 / 255, blue: 238 / 255, alpha: 1.0), for: .normal)
     phoneButton.addTarget(self, action: #selector(self.callPhone), for: .touchUpInside )

     @objc func callPhone(){

         UIApplication.shared.open(URL(string:"tel://3333333333")!, options: [:] , completionHandler: nil)


    }
于 2018-03-01T16:59:29.243 に答える