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

Полностью удалите разделители UISegmentedControl. (Iphone)

Есть ли способ полностью удалить строку, разделяющую два сегмента в UISegmentedControl?

Настройка segmentedControlStyle не помогает.

4b9b3361

Ответ 1

Нет, нет. Вы должны задуматься о создании функции UISegmentedControl вручную. Возможно, используйте два UIButtons.

Ответ 2

Если кто-то хочет этого типа UISegmentedControl View -

введите описание изображения здесь

EDITED: - Swift 3.0 расширения

    extension UISegmentedControl {

    func customizeAppearance(for height: Int) {

        setTitleTextAttributes([NSFontAttributeName:UIFont(name:"Helvetica Neue", size:13.0)!,NSForegroundColorAttributeName:UIColor.white], for:.normal)
        setTitleTextAttributes([NSFontAttributeName:UIFont(name:"Helvetica Neue", size:13.0)!,NSForegroundColorAttributeName:UIColor.white], for:.selected)
        setDividerImage(UIImage().colored(with: .clear, size: CGSize(width: 1, height: height)), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
        setBackgroundImage(UIImage().colored(with: .clear, size: CGSize(width: 1, height: height)), for: .normal, barMetrics: .default)
        setBackgroundImage(UIImage().colored(with: UIColor.init(red: 215/255.0, green: 0.0, blue: 30/255.0, alpha: 1.0), size: CGSize(width: 1, height: height)), for: .selected, barMetrics: .default);

        for  borderview in subviews {
            let upperBorder: CALayer = CALayer()
            upperBorder.backgroundColor = UIColor.init(red: 215/255.0, green: 0.0, blue: 30/255.0, alpha: 1.0).cgColor
            upperBorder.frame = CGRect(x: 0, y: borderview.frame.size.height-1, width: borderview.frame.size.width, height: 1)
            borderview.layer.addSublayer(upperBorder)
        }

    }
}

extension UIImage {

    func colored(with color: UIColor, size: CGSize) -> UIImage {
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor);
        let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
        context!.fill(rect);
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image!
    }
}

Расширение UIImage создает цветное изображение с нужным размером.

Принуждение параметра height в customizeAppearance избежать любого сбоя при построении context.

Вы можете сделать его еще более многоразовым, извлекая каждый атрибут настройки и ставьте его как параметры функции;)

Вот пример кода, проверенный на iOS 9 и отлично подходит для меня.

Добавьте эти строки кода в viewDidLoad -

[yourSegmentControl setTitleTextAttributes:@{ NSFontAttributeName:[UIFont fontWithName:@"Roboto-black" size:13.0],NSForegroundColorAttributeName:[UIColor whiteColor] }forState:UIControlStateSelected];

[yourSegmentControl setTitleTextAttributes:@{ NSFontAttributeName:[UIFont fontWithName:@"Roboto-black" size:13.0],NSForegroundColorAttributeName:[UIColor whiteColor] }forState:UIControlStateNormal];

[yourSegmentControl setDividerImage:[self imageWithColor:[UIColor clearColor]] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

[yourSegmentControl setBackgroundImage:[self imageWithColor:[UIColor clearColor]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

[yourSegmentControl setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:215/255.0 green:0 blue:30/255.0 alpha:1.0]] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];

for (UIView *borderview in yourSegmentControl.subviews) {

    CALayer *upperBorder = [CALayer layer];

    upperBorder.backgroundColor = [UIColor colorWithRed:215/255.0 green:0 blue:30/255.0 alpha:1.0].CGColor;

    upperBorder.frame = CGRectMake(0, borderview.frame.size.height-1, borderview.frame.size.width, 1.0f);

    [borderview.layer addSublayer:upperBorder];
}

и

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

Вот расширение Swift для достижения такого же вида в Swift-

yourSegmentControl.setTitleTextAttributes([NSFontAttributeName:UIFont(name:"Helvetica Neue", size:13.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Normal)

yourSegmentControl.setTitleTextAttributes([NSFontAttributeName:UIFont(name:"Helvetica Neue", size:13.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Selected)

yourSegmentControl.setDividerImage(self.imageWithColor(UIColor.clearColor()), forLeftSegmentState: UIControlState.Normal, rightSegmentState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)

yourSegmentControl.setBackgroundImage(self.imageWithColor(UIColor.clearColor()), forState:UIControlState.Normal, barMetrics:UIBarMetrics.Default)

yourSegmentControl.setBackgroundImage(self.imageWithColor(UIColor.init(red: 215/255.0, green: 0.0, blue: 30/255.0, alpha:1.0)), forState:UIControlState.Selected, barMetrics:UIBarMetrics.Default);

for  borderview in yourSegmentControl.subviews {

let upperBorder: CALayer = CALayer()
upperBorder.backgroundColor = UIColor.init(red: 215/255.0, green: 0.0, blue: 30/255.0, alpha: 1.0).CGColor
upperBorder.frame = CGRectMake(0, borderview.frame.size.height-1, borderview.frame.size.width, 1.0);
borderview.layer .addSublayer(upperBorder);

}

и

func imageWithColor(color: UIColor) -> UIImage {

    let rect = CGRectMake(0.0, 0.0, 1.0, yourSegmentControl.frame.size.height)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    let image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image

}

Ответ 3

Используйте этот метод для изменения изображения разделителя сегментов:

[segmentControl setDividerImage:dividerimg
            forLeftSegmentState:UIControlStateNormal
              rightSegmentState:UIControlStateNormal
                     barMetrics:UIBarMetricsDefault];

Ответ 4

Я объединил предыдущие ответы в расширение Swift.

Я хотел удалить все границы и разделители. Этот код просто использует цвета обычного сегмента, например. оттенок и фон для выбранного/снятого выделения.

Вызов

segmentedControl.removeBorders()

Здесь расширение

extension UISegmentedControl {
    func removeBorders() {
        setBackgroundImage(imageWithColor(backgroundColor!), forState: .Normal, barMetrics: .Default)
        setBackgroundImage(imageWithColor(tintColor!), forState: .Selected, barMetrics: .Default)
        setDividerImage(imageWithColor(UIColor.clearColor()), forLeftSegmentState: .Normal, rightSegmentState: .Normal, barMetrics: .Default)
    }

    // create a 1x1 image with this color
    private func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        CGContextSetFillColorWithColor(context, color.CGColor);
        CGContextFillRect(context, rect);
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image
    }
}

Ответ 5

Следующий код будет делать именно то, что вы хотите.

UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, self.segControlOut.frame.size.height), NO, 0.0);
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.segControlOut setDividerImage:blank
                forLeftSegmentState:UIControlStateNormal
                  rightSegmentState:UIControlStateNormal
                         barMetrics:UIBarMetricsDefault];

Ответ 6

Вы можете удалить все фон, границу и разделители из UISegmentedControl, установив черное изображение. Или вы можете установить пользовательские цвета.

В приведенном ниже примере удаляются все границы/разделители и устанавливается, чтобы фон был белым с 0,2 альфой, а выделенный сегмент был белым с альфа 1.0

[self.segmentedControl setBackgroundImage:[self imageWithColor:[UIColor colorWithWhite:1.0 alpha:0.2]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self.segmentedControl setBackgroundImage:[self imageWithColor:[UIColor colorWithWhite:1.0 alpha:1.0]] forState:UIControlStateSelected  barMetrics:UIBarMetricsDefault];

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

Ответ 7

Я использовал segmentcontrol.tintColor = [UIColor clearColor]; с iOS7 и, похоже, работает.

Ответ 8

@naveed и @Jon Настройка ответов сохранила мой день!

Но, будучи немного перфекционистом, я был расстроен, узнав, что этот код также оставляет дыры на внешней границе элемента управления:

До

Итак, я добавил несколько строк кода, чтобы избавиться от них и заставить его выглядеть аккуратно: После

Полный код для этого будет

CGFloat h = self.segControlOut.frame.size.height;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, h), NO, 0.0);

// draw the missing dots with the control border color
[self.segControlOut.tintColor set];
UIRectFrame( CGRectMake(0, -1, 1, 2.5) );
UIRectFrame( CGRectMake(0, h-1.5, 1, 2.5) );

UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.segControlOut setDividerImage:blank
                forLeftSegmentState:UIControlStateNormal
                  rightSegmentState:UIControlStateNormal
                         barMetrics:UIBarMetricsDefault];

Ответ 9

- (void) configSegmentControl {
    [segmentControl setBackgroundImage:[self imageWithColor:[UIColor blueColor]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [segmentControl setBackgroundImage:[self imageWithColor:[UIColor redColor]] forState:UIControlStateSelected  barMetrics:UIBarMetricsDefault];
    segmentControl.layer.cornerRadius = 4.0f;
    segmentControl.clipsToBounds = YES;
}

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}