2013-09-05 47 views
0

我有一個UILabel,其文本是www.google.com。現在,如果有人在文本上移動光標並按下它,Google的主頁應該打開。可能嗎?請解釋一下。如何在UILabel中設置超鏈接iphone中的文本

[emptyLabel setText:@"Sorry it looks like google is not currently available in any of your favourite places nearby, why not ask them to sign up at www.google.com"] 
+1

爲什麼你不使用服裝類型的UIButton ..? –

+0

第一件事是用戶永遠不會將光標移動到UILabel上。第二 - 如果你不想標籤的下劃線,只需將輕拍手勢附加到uilabel並添加目標。 – NightFury

+0

@ user2750542你應該使用自定義類型的UIButton。並設置其標題標籤(您現在將其作爲標籤文本提供)。 – hpp

回答

1

考慮使用Nimbus project中的​​。這是一個插入式UILabel替代品,可以自動檢測並創建可點擊鏈接。

1

您還可以使用UITextView並啓用數據檢測器並禁用編輯,使其具有UILabel的感覺。帶有必要的屬性設置的UItextview將自動檢測http鏈接,電話號碼等

如果必須使用UILabel,那麼您需要添加UITapgesture併爲點擊提供目標。

1
// While Loading the view 

[self underlineLabel:label withFont:[UIFont systemFontOfSize:17]]; 

UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myAction:)]; 
[label addGestureRecognizer:gr]; 
gr.numberOfTapsRequired = 1; 

// 

- (CGFloat)widthOfString:(NSString *)string withFont:(UIFont *)font { 
    CGSize stringSize = [string sizeWithFont:font]; 
    CGFloat width = stringSize.width; 
    return width; 
} 

- (CGFloat)heightOfString:(NSString *)string withFont:(UIFont *)font { 
    CGSize stringSize = [string sizeWithFont:font]; 
    CGFloat height = stringSize.height; 
    return height; 
} 

-(void)underlineLabel:(UILabel *)lbl withFont:(UIFont *)fnt { 
    float wdth = [self widthOfString:lbl.text withFont:fnt]; 
    float higt = [self heightOfString:lbl.text withFont:fnt]; 
    UIView *viw = [[UIView alloc]initWithFrame:CGRectMake((lbl.frame.size.width - wdth)/2, (lbl.frame.size.height/2) + (higt/2), wdth, 2)]; 
    [viw setBackgroundColor:[UIColor bluecolor]]; 
    [lbl addSubview:viw]; 
} 

// To Add action for gesture recognizer: 

- (void)myAction:(UITapGestureRecognizer *)gr { 
    // Define actions here 
} 
+0

謝謝大家的回答 – Mahe

+0

這個答案(創建一個看起來像鏈接的屬性文本標籤,設置User Interaction Enabled,添加一個TapGestureRecogniser)在Interface Builder中比在代碼中更容易執行,以供參考。 –

0

要麼使用UTTextView,它會自動檢測URL或爲URL創建按鈕。 謝謝。

相關問題