所以我有两个UIButton's
,两者都与班级LikeShape.swift
相关联
我有另一个名为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%确定当前用户在likedBy
和dislikedBy
LikeShape类有黑色按钮,而LikeShapeDone有红色按钮,但按钮只有黑色全部时间......有什么建议吗?
答案 0 :(得分:2)
根据我的评论中的建议,我将为您的Button创建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
Code Top的使用:
myLikeButton = LikeButton(frame: CGRectMake(0,0,200,50))
myLikeButton.setLike("blue")
或(在运行时间)
myLikeButton.setLike("red")