ios - 在运行时更改 UIButton 类

标签 ios xcode swift uibutton

所以我有两个 UIButton 的,都连接到类 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 有红色按钮,但是按钮一直都是黑色的...有什么建议吗?

最佳答案

按照我评论中的建议,我会为您的按钮创建 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/

相关文章:

ios - 如何从 2 个不同的 View Controller 观察 NSManagedObject 记录的变化?

ios swift : return to previous view controller

ios - 跟进手机格式化: More than 1 phone number field.

objective-c - 向 MKMapView 添加多个叠加层

android - 使用 Phonegap/Cordova 相机插件从相机或图库中选择照片

c++ - boost::asio 暂停时抛出异常

ios - 下载 dSYM 失败 "Missing App Version"

ios - 使用 Swift 调用电话号码

ios - 无法在 iOS 应用程序中启动 native Google map - 而是打开 Safari

iphone - 从 iOS 中的 App Delegate 调用当前 View Controller 中的方法