所以我有两个 UIButton 的
,都连接到类 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 有红色按钮,但是按钮一直都是黑色的...有什么建议吗?
最佳答案
按照我评论中的建议,我会为您的按钮创建 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")
关于ios - 在运行时更改 UIButton 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36622515/