iOS 7 圆框按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19142759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:58:45  来源:igfitidea点击:

iOS 7 round framed button

iosobjective-ccocoa-touchuibutton

提问by h345k34cr

the iOS App Store has a blue round framed button for buying/downloading apps.

iOS App Store 有一个蓝色圆形框按钮,用于购买/下载应用程序。

In my App you can download additional content and I want to have a similar button, just because it looks familiar to the user.

在我的应用程序中,您可以下载其他内容,我希望有一个类似的按钮,因为它对用户来说看起来很熟悉。

If you don't know, what I mean: these buttons, like "$3.99"

如果你不知道,我的意思是:这些按钮,比如“$3.99”

enter image description here

在此处输入图片说明

How is this possible?

这怎么可能?

回答by Dima

You can manipulate the CALayer of your button to do this pretty easily.

您可以操作按钮的 CALayer 来轻松完成此操作。

// assuming you have a UIButton or more generally a UIView called buyButton

buyButton.layer.cornerRadius = 2;
buyButton.layer.borderWidth = 1;
buyButton.layer.borderColor = [UIColor blueColor].CGColor;
// (note - may prefer to use the tintColor of the control)

you can tweak each of those to get the color and border effect you want.

你可以调整每一个以获得你想要的颜色和边框效果。

You will also have to add an import in any file you want to use CALayers

您还必须在要使用 CALayer 的任何文件中添加导入

#import <QuartzCore/QuartzCore.h>

回答by abbood

If you are a big fan of using storyboards for your UI design with iOS.. you can set the corner radius (and whichever other parameters as mentioned in dima's answer-- although unfortunately not the color, since it's a CGColor and Apple presently does not have that option in the popup) in the identity inspector->user defined runtime attributesin storyboard as shown here:

如果您非常喜欢在 iOS 的 UI 设计中使用故事板..您可以设置角半径(以及 dima 的回答中提到的任何其他参数——尽管不幸的是不是颜色,因为它是 CGColor,而 Apple 目前没有在弹出窗口中有该选项)在identity inspector->user defined runtime attributes情节提要中,如下所示:

enter image description here

在此处输入图片说明

bonus:you use runtime attributes for UIButtonplaceholder text color (see here) and to change fonts of UILabel, UITextFieldand UIButtonas well (see here)

奖金:您使用运行时属性的UIButton占位符文本颜色(参见这里),并改变字体UILabelUITextField并且UIButton还有(见这里

回答by Gideon King

For standard iOS control elements like UIButton, UILabel, you should use the UIViewtintColorproperty:

对于标准iOS控制元件喜欢UIButtonUILabel你应该使用UIViewtintColor属性:

buyButton.layer.borderColor = buyButton.tintColor.CGColor;

回答by AlexWien

For simple border like you described, use the answer from Dima using CALAyer.

对于您描述的简单边框,请使用来自 Dima 的 CALAyer 的答案。

If you want more, e.g a rounded rectangle with gradient then use this approach as base:

如果您想要更多,例如带渐变的圆角矩形,则使用此方法作为基础:

Create a custom View which draws a rounded rectangle and place it over the button. Use the search function here to search for draw rounded rectangle. The drawing works by drawing 4 arcs with defined radius (corners) and 4 straight lines.

创建一个自定义视图,它绘制一个圆角矩形并将其放在按钮上。使用这里的搜索功能来搜索绘制圆角矩形。绘图的工作原理是绘制 4 条具有定义半径(角)和 4 条直线的圆弧。



FTR, here's how you make a UIView with the correct iOS7 rounded corners, per Alex and Brian.

FTR,按照 Alex 和 Brian 的说法,以下是如何使用正确的 iOS7 圆角制作 UIView。

I'm pretty sure that CGPathCreateWithRoundedRect does notgive you the "new" rounded corners. You have to use bezierPathWithRoundedRect for the "new" corners.

我很确定 CGPathCreateWithRoundedRect不会给你“新的”圆角。您必须将 bezierPathWithRoundedRect 用于“新”角。

#import "UIViewWithIOS7RoundedCorners.h"
@implementation UIViewWithIOS7RoundedCorners
-(void)drawRect:(CGRect)rect
    {
    // for a filled shape...

    UIBezierPath* path =
        [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:4];
    [[UIColor blueColor] setFill];
    [path fill];

    // for just a border...

    int thickness=2;
    UIBezierPath* path =
        [UIBezierPath bezierPathWithRoundedRect:
            CGRectInset(self.bounds, thickness/2, thickness/2)
            cornerRadius: 4];
    path.lineWidth = thickness;
    [[UIColor blueColor] setStroke];
    [path stroke];
    }

@end
// ps don't forget to set .backgroundColor=[UIColor clearColor]
// perhaps in initWithCoder/initWithFrame

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

Hope it helps someone

希望它可以帮助某人

回答by jianpx

I have implemented the AppStore style button here for your reference: ASButton.m

我在这里实现了 AppStore 样式按钮供您参考:ASButton.m

and the project is here

这个项目在这里

Hope to help :]

希望有所帮助:]

回答by Duncan C

To extend @abbood 's excellent answer, it is actually possible to set the border color and background color of a view's layer from IB, but it requires a little prep work to do so.

为了扩展@abbood 的优秀答案,实际上可以从 IB 设置视图层的边框颜色和背景颜色,但需要做一些准备工作。

I've created a custom category on NSView, CALayer+setUIColor.h.

我在 NSView,CALayer+setUIColor.h 上创建了一个自定义类别。

The that sets border colors only has one method, setBorderUIColor. It takes a UIColor as an input, fetches the UIColor's underlying NSColor, and applies that color to the view's layer.

设置边框颜色的方法只有一种,setBorderUIColor。它接受一个 UIColor 作为输入,获取 UIColor 的底层 NSColor,并将该颜色应用到视图层。

Then, in IB, you just add a user defined runtime attribute like this:

然后,在 IB 中,您只需添加一个用户定义的运行时属性,如下所示:

KeyPath layer.borderUIColor Type color Value The desired color.

KeyPath layer.borderUIColor 类型 color Value 想要的颜色。

At runtime the system invokes your method, passing in the UIColor that's defined in IB. The category gets the CGColor from the UIColor and applies it to the layer.

在运行时,系统调用您的方法,传入在 IB 中定义的 UIColor。该类别从 UIColor 获取 CGColor 并将其应用于图层。

You can see this in a working project in a github project of mine called

您可以在我的 github 项目中的一个工作项目中看到这一点,该项目称为

RandomBlobs

随机斑点

I've also done the same thing for setting a layer's background color property, but not in the above project.

我也做了同样的事情来设置图层的背景颜色属性,但在上面的项目中没有。

回答by Aneel

And for the swift version of Duncan C's extension of abbood's answer:

对于 Duncan C 对 abbood 答案的扩展的 swift 版本:

extension CALayer {
    var borderUIColor: UIColor? {
        get {
            if let borderColor = borderColor {
                return UIColor(CGColor: borderColor)
            }
            return nil
        }
        set {
            borderColor = newValue?.CGColor ?? nil
        }
    }
}

回答by Imanou Petit

With Swift 5.1 / iOS 13, you can create a subclass of UIButtonin order to have a custom button that will look like the blue rounded border button in iOS AppStore app.

使用 Swift 5.1 / iOS 13,您可以创建一个子类,UIButton以便拥有一个看起来像 iOS AppStore 应用程序中的蓝色圆形边框按钮的自定义按钮。

The following code shows how to manage properly the tint color (when the button appears behind the dimmed view of a UIAlertController), the title's color, the highlighted background color, the border's style, the border's color and the content insets.

以下代码显示了如何正确管理色调颜色(当按钮出现在 a 的变暗视图后面时UIAlertController)、标题的颜色、突出显示的背景颜色、边框的样式、边框的颜色和内容插入。

CustomButton.swift:

自定义按钮.swift:

import UIKit

class CustomButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setProperties()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setProperties()
    }

    func setProperties() {
        // Set the layer's properties
        layer.borderColor = tintColor?.cgColor
        layer.borderWidth = 1
        layer.cornerRadius = 4

        // Set colors for title's states
        setTitleColor(tintColor, for: .normal)
        setTitleColor(.white, for: .highlighted)

        // Add some margins between the title (content) and the border
        contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
    }

    override var isHighlighted: Bool {
        didSet {
            // Toggle the background color according to button's highlighted state
            backgroundColor = super.isHighlighted ? tintColor : nil
        }
    }

    override func tintColorDidChange() {
        super.tintColorDidChange()

        // When the tint color is changed by the system (e.g. when the button appears below the dimmed view of a UIAlertController), we have to manually update border color and title's text color
        layer.borderColor = tintColor?.cgColor
        setTitleColor(tintColor, for: .normal)
    }

}

ViewController.swift:

视图控制器.swift:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .secondarySystemBackground

        let button = CustomButton()
        button.setTitle("Normal", for: .normal)
        button.setTitle("Highlighted", for: .highlighted)
        button.addTarget(self, action: #selector(presentAlert(_:)), for: .touchUpInside)
        view.addSubview(button)

        // auto layout
        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
    }

    /// Present alert when button is tapped
    @objc func presentAlert(_ sender: UIButton) {
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
        let alertAction = UIAlertAction(title: "OK", style: .default)
        alertController.addAction(alertAction)
        present(alertController, animated: true, completion: nil)
    }

}

The images below show how the custom button will appear in normal state, when the system tinColoris changed (behind the dimmed view of a UIAlertController) and in highlightedstate.

下图显示了自定义按钮在正常状态下、系统tinColor更改时(在 a 的变暗视图后面UIAlertController)和highlighted状态下的显示方式。

enter image description here

在此处输入图片说明