2016-04-14 89 views
0

變化的UIButton類,所以我有兩個UIButton's,都連接到類LikeShape.swift enter image description here在運行時

我有另一個類名爲LikeShapeDone.swift,我想這樣在運行時設置:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
    { 
     let imageCell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as! PostsCollectionViewCell 

     if (likedBy[indexPath.row].containsObject((PFUser.currentUser()?.username)!)){ 
       // Post is liked by the current user 
       imageCell.likeButton = LikeShape() 
       imageCell.dislikeButton = LikeShapeDone() 
      } 
      if (dislikedBy[indexPath.row].containsObject((PFUser.currentUser()?.username)!)){ 
       // Post is disliked by the current user 
       imageCell.dislikeButton = LikeShapeDone() 
       imageCell.likeButton = LikeShape() 
      } 
      else{ 
       // Post is not liked by the current user 
      } 
     // <---- End ImageCell Row ----> 
     return imageCell 
    } 

但沒有任何反應..我100%確定當前用戶在likedBydislikedBy LikeShape類有黑色按鈕,而LikeShapeDone有紅色按鈕,但按鈕只是一直黑色......任何建議?

+0

建議:創建一個按鈕,並改變在運行時鍵入不是整個類或整個按鈕。 –

+0

@AshishKakkad你的意思是:'imageCell.likeButton = LikeShape()'?這是我的嘗試,並沒有工作。 –

+0

創建一個按鈕LikeDislikeButton.type =喜歡或不喜歡。在運行時更改 –

回答

2

正如我在評論中推薦的那樣,我會爲您的按鈕創建1個類,您可以在哪裏直接在運行時設置按鈕的類型。例如:

public class LikeButton: UIButton { 

    public func setLike(type: String) { 

    switch(type) { 

    case "blue": 
     self.setBackgroundColor(UIColor.blueColor(), forState: .Normal) 
    break; 

    case "red": 
     self.setBackgroundColor(UIColor.redColor(), forState: .Normal) 
     break; 

    case "black": 
     self.setBackgroundColor(UIColor.blackColor(), forState: .Normal) 
     break; 

    case "white": 
     self.setBackgroundColor(UIColor.whiteColor(), forState: .Normal) 
     break; 

    default: 
    break 
    } 
} 

再次編輯:這隻有在您確實需要擴展當前UIButton時纔有意義。當你有多個參數時,這是有道理的,你不想每次都將它們設置到你的UIButton類。

您可以設置(當然):

myButton.setBackgroundColor(UIColor.redColor(), forState: .Normal) //Any Color 

代碼頂級的用法:

myLikeButton = LikeButton(frame: CGRectMake(0,0,200,50)) 
myLikeButton.setLike("blue") 

或(在運行時)

myLikeButton.setLike("red") 
+0

你可以添加示例代碼,你定義4種不同的類型?要在黑色,白色,紅色和藍色之間切換? –

+0

我是否創建一個Swift類或Cocoa類? –

+0

Doesent事。 CocoaTouch類只帶來一個代碼 – derdida