2016-04-14 90 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