让按钮标题标签尺寸符合swift(iPad或iPhone)中的设备

时间:2018-02-26 07:05:46

标签: ios swift uibutton autolayout uilabel

我对按钮标题标签尺寸有疑问 我想扩大iPad中按钮标题标签的字体大小 我尝试使用以下代码,但似乎无法使标签放大 如果我想根据设备改变字体大小,我该怎么办?

以图像为例。
标签尺寸如下图所示 image

这个代码在iPhone上工作得很好,但在iPad上看起来很小。

func CustomButton() -> UIButton {
    let ui = UIButton()
    ui.translatesAutoresizingMaskIntoConstraints = false
    ui.contentMode = UIViewContentMode.scaleAspectFit
    return ui
}

class FullWidthButton: UIView {

var button:UIButton = { () -> UIButton in
    let ui:UIButton = CustomButton()
    ui.titleLabel?.numberOfLines = 1
    ui.titleLabel?.textAlignment = .center
    ui.titleLabel!.minimumScaleFactor = 0.5
    ui.titleLabel?.textColor = UIColor.white
    ui.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
    ui.titleLabel?.adjustsFontSizeToFitWidth = true
    ui.titleLabel?.lineBreakMode = .byClipping
    ui.backgroundColor = defaultButtonOrangeColor
    ui.layer.cornerRadius = defaultButtonRadius
    ui.layer.masksToBounds = true
    return ui
}()
override init(frame: CGRect) {
    super.init(frame:frame)
    translatesAutoresizingMaskIntoConstraints = false
    loadContent()
}

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

override func layoutSubviews() {
    super.layoutSubviews()

    loadVFL()
}

func loadContent() {

    addSubview(button)
}

func loadVFL() {

    button.snp.makeConstraints { (make) in
        make.width.height.leading.trailing.top.bottom.equalToSuperview()
    }   
} 
}

3 个答案:

答案 0 :(得分:0)

只需替换

ui.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)

if UIDevice.current.userInterfaceIdiom == .pad{
        ui.titleLabel?.font = UIFont.systemFont(ofSize: 20.0)
}else if  UIDevice.current.userInterfaceIdiom == .phone{
        ui.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
}else{
        //Unspecified
        ui.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
}

答案 1 :(得分:0)

switch UIDevice.current.userInterfaceIdiom { 
    case .phone:
    case .pad:
    case .unspecified:
}

答案 2 :(得分:0)

尝试这样

if UIScreen.mainScreen().bounds.size.height == 480 {
    // iPhone 4
    label.font = label.font.fontWithSize(20)     
} else if UIScreen.mainScreen().bounds.size.height == 568 {
    // IPhone 5
    label.font = label.font.fontWithSize(20)
} else if UIScreen.mainScreen().bounds.size.width == 375 {
    // iPhone 6
    label.font = label.font.fontWithSize(20)
} else if UIScreen.mainScreen().bounds.size.width == 414 {
    // iPhone 6+
    label.font = label.font.fontWithSize(20)
} else if UIScreen.mainScreen().bounds.size.width == 768 {
    // iPad
    label.font = label.font.fontWithSize(20)
}