Добавить цель к кнопке в Swift - PullRequest
0 голосов
/ 29 ноября 2018

Я хочу реализовать разные цели в разных случаях для кнопки.

Если это собственный профиль текущего пользователя, кнопка должна добавить цель "перейти к настройкам".Если это другой пользователь, я хочу добавить следующее / отписаться от действия.

После проверки всех параметров мой код должен работать.Но это не работает.Я добавил несколько отпечатков, но кнопка не активна.

func setupUserInformation(user: UserModel) {
    usernameLabel.text = user.username

    if user.uid == UserApi.shared.CURRENT_USER_ID {
        editButton.setTitle("Einstellungen", for: .normal)

        editButton.addTarget(self, action: #selector(goToSettings), for: .touchUpInside)

    } else {
        if user.isFollowing! == true {
            setupUnfollowButton()
        } else {
            setupFollowButton()
        }
    }
}

@objc func goToSettings() {
    delegate?.goToSettingVC()
}

func setupFollowButton() {
    editButton.layer.borderWidth = 1
    editButton.layer.borderColor = UIColor.lightGray.cgColor
    editButton.layer.cornerRadius = 5
    editButton.clipsToBounds = true

    editButton.setTitleColor(UIColor.white, for: .normal)
    editButton.backgroundColor = UIColor(red: 1 / 255, green: 84 / 255, blue: 147 / 255, alpha: 1.0)
    editButton.setTitle("Folgen", for: UIControl.State.normal)
    editButton.addTarget(self, action: #selector(followAction), for: .touchUpInside)
}

@objc func followAction() {
    print("Button wurde gedrückt")
    if user?.isFollowing == false {
        FollowApi.shared.followAction(withUser: user!.uid!)
        setupUnfollowButton()
        user?.isFollowing = true

    }
}

func setupUnfollowButton() {
    editButton.layer.borderWidth = 1
    editButton.layer.borderColor = UIColor.lightGray.cgColor
    editButton.layer.cornerRadius = 5
    editButton.clipsToBounds = true

    editButton.setTitleColor(UIColor.black, for: .normal)
    editButton.backgroundColor = UIColor.white
    editButton.setTitle("Entfolgen", for: UIControl.State.normal)
    editButton.addTarget(self, action: #selector(unFollowAction), for: .touchUpInside)
}

@objc func unFollowAction() {
    print("Button wurde gedrückt")
    if user?.isFollowing == true {
        FollowApi.shared.unfollowAction(withUser: user!.uid!)
        setupFollowButton()
        user?.isFollowing = false

    }
}

Большое спасибо заранее за вашу помощь!

ОБНОВЛЕНИЕ

Внесены некоторые изменения, как в ответах ниже.Но все же цель добавления не будет выполнена.

var user: UserModel? {
    didSet {
        guard let _user = user else { return }
        setupUserInformation(user: _user)
    }
}

func setupUserInformation(user: UserModel) {

    editButton.addTarget(self, action: #selector(didTapEditButton), for: .touchUpInside)

    if user.uid == UserApi.shared.CURRENT_USER_ID {
        editButton.setTitle("Einstellungen", for: .normal)

    }else {
        if user.isFollowing! == true {
            setupUnfollowButton()
        } else {
            setupFollowButton()
        }
    }

}

@objc func didTapEditButton() {

    //Add IF conditions according to what your button should do in different cases here.
    if user!.uid == UserApi.shared.CURRENT_USER_ID {
        editButton.setTitle("Einstellungen", for: .normal)
        goToSettings()
    }else {
        if user!.isFollowing! == true {
            unFollowAction()
        } else {
            followAction()
        }
    }

}

@objc func goToSettings() {
    delegate?.goToSettingVC()
}

func setupFollowButton() {
    editButton.layer.borderWidth = 1
    editButton.layer.borderColor = UIColor.lightGray.cgColor
    editButton.layer.cornerRadius = 5
    editButton.clipsToBounds = true

    editButton.setTitleColor(UIColor.white, for: .normal)
    editButton.backgroundColor = UIColor(red: 1 / 255, green: 84 / 255, blue: 147 / 255, alpha: 1.0)
    editButton.setTitle("Folgen", for: UIControl.State.normal)
}

func followAction() {
    print("Button wurde gedrückt")
    if user?.isFollowing == false {
        FollowApi.shared.followAction(withUser: user!.uid!)
        setupUnfollowButton()
        user?.isFollowing = true

    }
}

func setupUnfollowButton() {
    editButton.layer.borderWidth = 1
    editButton.layer.borderColor = UIColor.lightGray.cgColor
    editButton.layer.cornerRadius = 5
    editButton.clipsToBounds = true

    editButton.setTitleColor(UIColor.black, for: .normal)
    editButton.backgroundColor = UIColor.white
    editButton.setTitle("Entfolgen", for: UIControl.State.normal)
}

func unFollowAction() {
    print("Button wurde gedrückt")
    if user?.isFollowing == true {
        FollowApi.shared.unfollowAction(withUser: user!.uid!)
        setupFollowButton()
        user?.isFollowing = false

    }
}

Ответы [ 3 ]

0 голосов
/ 30 ноября 2018

Мэтт прав !!Ваш подход здесь совершенно неверен.Пожалуйста, попробуйте изменить ваш подход.

Ваш подход должен выглядеть примерно так:

override func viewDidLoad() {
    super.viewDidLoad()

    //Set Target to your button only once.
    editButton.addTarget(self, action: #selector(didTapEditButton), for: .touchUpInside)

}

@objc func didTapEditButton() {

    //Add IF conditions according to what your button should do in different cases here. 
    if user.uid == UserApi.shared.CURRENT_USER_ID {
        goToSettings()
    }else {
        if user.isFollowing! == true {
            setupUnfollowButton()
        } else {
            setupFollowButton()
        }
    }

}


func setupFollowButton() {

    //Make the check to see what state your button is currently in by checking if the title of the button is "Follow" or "Unfollow"
    if editButton.titleLabel?.text == "Unfollow"{
        editButton.layer.borderWidth = 1
        editButton.layer.borderColor = UIColor.lightGray.cgColor
        editButton.layer.cornerRadius = 5
        editButton.clipsToBounds = true

        editButton.setTitleColor(UIColor.white, for: .normal)
        editButton.backgroundColor = UIColor(red: 1 / 255, green: 84 / 255, blue: 147 / 255, alpha: 1.0)
        editButton.setTitle("Follow", for: UIControl.State.normal)

        followAction()
    }
}


 func setupUnfollowButton() {

    //Do the same here for the other state.
    if editButton.titleLabel?.text == "Follow"{
        editButton.layer.borderWidth = 1
        editButton.layer.borderColor = UIColor.lightGray.cgColor
        editButton.layer.cornerRadius = 5
        editButton.clipsToBounds = true

        editButton.setTitleColor(UIColor.black, for: .normal)
        editButton.backgroundColor = UIColor.white
        editButton.setTitle("Unfollow", for: UIControl.State.normal)

        unFollowAction()
    }
}


func followAction() {
    print("Button wurde gedrückt")
    if user?.isFollowing == false {
        FollowApi.shared.followAction(withUser: user!.uid!)
        setupUnfollowButton()
        user?.isFollowing = true

    }
}

func unFollowAction() {
    print("Button wurde gedrückt")
    if user?.isFollowing == true {
        FollowApi.shared.unfollowAction(withUser: user!.uid!)
        setupFollowButton()
        user?.isFollowing = false
    }
}
0 голосов
/ 30 ноября 2018

Решена проблема со следующей строкой кода:

cell.contentView.isUserInteractionEnabled = false

Просто забыли отключить взаимодействие пользователя с представлением коллекции.Когда я нажал кнопку, был активирован заголовок представления коллекции, а не кнопка.

Спасибо, ребята, за вашу помощь!

0 голосов
/ 29 ноября 2018

Обратите внимание, что добавление цели не выполняет код действия;он просто устанавливает кнопку для того, что он будет делать, когда пользователь нажмет ее позже.

Как только вы поймете это, вы, вероятно, увидите, что весь ваш подход здесь, вероятно, плохая идея.Не пытайтесь ставить цель и действие условно.Вместо этого просто установите цель и действие раз и навсегда.Затем внутри метода действия, где вы ставите условия, чтобы решить, что делать при каждом нажатии кнопки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...