Подтвердить что ты не робот

Поместите идентификатор UIActivityIndicator внутри UIButton

Я знаю, что мне не хватает чего-то глупого, но в любом случае вот мой код:

UIActivityIndicatorView indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.hidesWhenStopped = YES;
indicator.frame = btnLogin.frame;
indicator.center = btnLogin.center;
[self.view addSubview:indicator];
[indicator bringSubviewToFront:indicator];

Вот конечный результат:

Screenshot of misplaced UIActivityIndicator

http://img542.imageshack.us/img542/8172/uiactivity.png

Заранее благодарю вас!

4b9b3361

Ответ 1

Я думаю, что концепция, которую вам не хватает, состоит в том, что рамка представления (и ее центр) связаны с ее надзором. Основываясь на вашем скриншоте, я бы предположил, что ваши текстовые поля и кнопки находятся в представлении, которое действует как контейнер. Таким образом, ваша рамка и центр кнопок относятся к такому виду контейнера, а не к виду контроллера представления в целом. Вы назначаете один и тот же фрейм и центр индикатору активности, но затем вы добавляете индикатор в качестве подсмотра основного вида, а не вида контейнера. Таким образом, теперь у вас есть два вида (кнопка и индикатор) с одним и тем же фреймом, но этот кадр относится к двум различным супервидам.

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

UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGFloat halfButtonHeight = btnLogin.bounds.size.height / 2;
CGFloat buttonWidth = btnLogin.bounds.size.width;
indicator.center = CGPointMake(buttonWidth - halfButtonHeight , halfButtonHeight);
[btnLogin addSubview:indicator];
[indicator startAnimating];

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

Ответ 2

Основываясь на ответе @Musa almatri, я создаю расширение:

extension UIButton {
func loadingIndicator(show show: Bool) {
    let tag = 9876
    if show {
        let indicator = UIActivityIndicatorView()
        let buttonHeight = self.bounds.size.height
        let buttonWidth = self.bounds.size.width
        indicator.center = CGPointMake(buttonWidth/2, buttonHeight/2)
        indicator.tag = tag
        self.addSubview(indicator)
        indicator.startAnimating()
    } else {
        if let indicator = self.viewWithTag(tag) as? UIActivityIndicatorView {
            indicator.stopAnimating()
            indicator.removeFromSuperview()
        }
    }
}}

то вы можете использовать его следующим образом:

yourButton.loadingIndicator(show: true) //hide -> show: false

Ответ 3

Вот версия Swift 3 без использования тегов.

import UIKit

extension UIButton {
    func loadingIndicator(show: Bool) {
        if show {
            let indicator = UIActivityIndicatorView()
            let buttonHeight = self.bounds.size.height
            let buttonWidth = self.bounds.size.width
            indicator.center = CGPoint(x: buttonWidth/2, y: buttonHeight/2)
            self.addSubview(indicator)
            indicator.startAnimating()
        } else {
            for view in self.subviews {
                if let indicator = view as? UIActivityIndicatorView {
                    indicator.stopAnimating()
                    indicator.removeFromSuperview()
                }
            }
        }
    }
}

Ответ 4

Быстрое решение:

var indicator = UIActivityIndicatorView()
var halfButtonHeight = btnLogin.bounds.size.height / 2;
var buttonWidth = btnLogin.bounds.size.width;
indicator.center = CGPointMake(buttonWidth - halfButtonHeight , halfButtonHeight);
x.addSubview(indicator)
indicator.startAnimating()

И чтобы сделать это в центре кнопки

indicator.center = CGPointMake(buttonWidth/2, halfButtonHeight);

Или используйте большую библиотеку

https://github.com/souzainf3/RNLoadingButton-Swift

Ответ 5

Я использую противопоказания для центрирования индикатора внутри UIButton. Адаптируя расширение @DanielQ, которое становится:

extension UIButton {
    func loadingIndicator(show: Bool) {
        let tag = 9876
        if show {
            let indicator = UIActivityIndicatorView()
            indicator.tag = tag
            self.addSubview(indicator)
            indicator.translatesAutoresizingMaskIntoConstraints = false
            let horizontalConstraint = NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
            let verticalConstraint = NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
            self.addConstraints([horizontalConstraint, verticalConstraint])
            indicator.startAnimating()
        } else {
            if let indicator = self.viewWithTag(tag) as? UIActivityIndicatorView {
                indicator.stopAnimating()
                indicator.removeFromSuperview()
            }
        }
    }
}

Ответ 6

Небольшое обновление: (добавление кнопки в режиме просмотра)

extension UIButton {
    func loadingIndicator(_ show: Bool) {
        let indicatorTag = 808404
        if show {
            isEnabled = false
            alpha = 0
            let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
            indicator.center = center
            indicator.tag = indicatorTag
            superview?.addSubview(indicator)
            indicator.startAnimating()
        } else {
            isEnabled = true
            alpha = 1.0
            if let indicator = superview?.viewWithTag(indicatorTag) as? UIActivityIndicatorView {
                indicator.stopAnimating()
                indicator.removeFromSuperview()
            }
        }
    }
}

Ответ 7

Я удалил название с помощью кнопки, а затем добавил его после завершения анимации, а не индикатор, переопределяющий заголовок:

extension UIButton {

func loadingIndicator(show: Bool) {
    let tag = 9876

    var color: UIColor?

    if show {
        color = titleColor(for: .normal)
        let indicator = UIActivityIndicatorView()
        let buttonHeight = self.bounds.size.height
        let buttonWidth = self.bounds.size.width
        indicator.center = CGPoint(x: buttonWidth/2, y: buttonHeight/2)
        indicator.tag = tag
        indicator.color = UIColor.white
        setTitleColor(.clear, for: .normal)

        self.addSubview(indicator)
        indicator.startAnimating()
    } else {
        if let indicator = self.viewWithTag(tag) as? UIActivityIndicatorView {
            indicator.stopAnimating()
            indicator.removeFromSuperview()
            setTitleColor(color, for: .normal)
        }
    }
}
}