2013-03-21 83 views
0

我正在使用xcode 4.6開發一個應用程序。在這裏我想以編程方式添加UIButton到UIscrollview。這是我遵循的代碼。UIscrollview中的自定義UIButton

UIButton *bt =[[UIButton alloc]initWithFrame:frame]; 
bt=[UIButton buttonWithType:UIButtonTypeCustom]; 
[bt setTitle:@"Custom Button" forState:UIControlStateNormal]; 
[bt addTarget:self action:@selector(userTappedOnLink:) forControlEvents:UIControlEventTouchUpInside]; 
bt.backgroundColor = [UIColor grayColor]; 
bt.titleLabel.textColor=[UIColor blueColor]; 
[self.mainscrollview addSubview:bt]; 
[self.mainscrollview bringSubviewToFront:bt]; 

現在的問題是,按鈕消失(技術上它的textcolor變成白色)點擊。我檢查保持UIscrollview顏色爲紅色,該按鈕仍然在視圖中,但我不能得到它的文字顏色改變的原因,我如何撤消DIS。 基本上我想用UIbutton創建一個可點擊的鏈接。 我知道uitextview方法(datadetectortype),但它沒用,因爲我想在鏈接和實際鏈接的標籤中顯示不同的文本。

注意:文本顏色不會變回藍色並且只保留白色。

在此先感謝。

回答

2

試試下面的代碼

UIButton *bt =[UIButton buttonWithType:UIButtonTypeCustom]; 
bt.frame = CGRectMake(50.0, 50.0, 100.0, 50.0); 
[bt setTitle:@"Custom Button" forState:UIControlStateNormal]; 
[bt addTarget:self action:@selector(userTappedOnLink:) forControlEvents:UIControlEventTouchUpInside]; 
bt.backgroundColor = [UIColor grayColor]; 
bt.titleLabel.textColor=[UIColor blueColor]; 
[self.scrollTest addSubview:bt]; 

-(void)userTappedOnLink:(UIButton*)sender 
{ 
    NSLog(@"Test .."); 

    [self performSelector:@selector(changeBtnTextColor:) withObject:sender afterDelay:1.0]; 
} 

-(void)changeBtnTextColor:(UIButton*)btn 
{ 
    btn.titleLabel.textColor=[UIColor blueColor]; 
} 

希望它會爲你工作。

+0

謝謝你的答案..這是一個gr8幫助兄弟!現在完美的作品。 – xrnd 2013-03-21 06:08:49

0

使用下面的代碼:

[bt setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 

問題是你設置標題到titleLabel並且想更改按鈕名稱顏色的文字顏色。

所有最好的!

0

check Button's fram ..是否有效? 並從您的代碼中刪除bt=[UIButton buttonWithType:UIButtonTypeCustom];行。下面的代碼

2

使用你會得到你的解決方案

UIButton *bt =[[UIButton alloc]initWithFrame:frame]; 
bt=[UIButton buttonWithType:UIButtonTypeCustom]; 
[bt setTitle:@"Custom Button" forState:UIControlStateNormal]; 
[bt addTarget:self action:@selector(userTappedOnLink:) forControlEvents:UIControlEventTouchUpInside]; 
[bt setBackgroundColor:[UIColor grayColor]]; 
[bt setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 
[self.mainscrollview addSubview:bt]; 
[self.mainscrollview bringSubviewToFront:bt]; 
+0

那麼,你的代碼工作正常,只要我保持按鈕正常,而不是自定義。但是現在,當我點擊按鈕時,該事件正在被調用,但沒有視覺上的按鈕被點擊。 – xrnd 2013-03-21 06:06:03

+0

然後設置其他顏色的標題爲UIControlStateHighlighted Like [bt setTitleColor:[UIColor redColor] UIControlStateHighlighted]; – Pratik 2013-03-21 06:32:20

+0

在這種情況下,顏色始終保持藍色。但我再次改變了該按鈕的被調用函數中的顏色,並且在按下按鈕時產生了點擊效果。 – xrnd 2013-03-21 06:37:26