Swift - UIButton with two lines of text

前端 未结 10 1657
离开以前
离开以前 2020-11-30 23:38

I was wondering if it is possible to create a UIButton with two lines of text. I need each line to have a different font size. The first line will be 17 point and the seco

相关标签:
10条回答
  • 2020-12-01 00:32

    One way to do it is with labels, I guess. I did this, and it seems to work ok. I could create this as a UIButton and then expose the labels, I guess. I don't know if this makes any sense.

        let firstLabel = UILabel()
    
        firstLabel.backgroundColor = UIColor.lightGrayColor()
        firstLabel.text = "Hi"
        firstLabel.textColor = UIColor.blueColor()
        firstLabel.textAlignment = NSTextAlignment.Center
        firstLabel.frame = CGRectMake(0, testButton.frame.height * 0.25, testButton.frame.width, testButton.frame.height * 0.2)
        testButton.addSubview(firstLabel)
    
        let secondLabel = UILabel()
    
        secondLabel.backgroundColor = UIColor.lightGrayColor()
        secondLabel.textColor = UIColor.blueColor()
        secondLabel.font = UIFont(name: "Arial", size: 12)
        secondLabel.text = "There"
        secondLabel.textAlignment = NSTextAlignment.Center
        secondLabel.frame = CGRectMake(0, testButton.frame.height * 0.5, testButton.frame.width, testButton.frame.height * 0.2)
        testButton.addSubview(secondLabel)
    
    0 讨论(0)
  • 2020-12-01 00:33

    change line break to character wrap , select your button and in attribute inspector go to line break and change it to character wrap

    enter image description here

    0 讨论(0)
  • 2020-12-01 00:39

    I was looking for nearly the same topic, except that I don't need two different font sizes. In case someone is looking for a simple solution:

        let button = UIButton()
        button.titleLabel?.numberOfLines = 0
        button.titleLabel?.lineBreakMode = .byWordWrapping
        button.setTitle("Foo\nBar", for: .normal)
        button.titleLabel?.textAlignment = .center
        button.sizeToFit()
        button.addTarget(self, action: #selector(rightBarButtonTapped), for: .allEvents)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    
    0 讨论(0)
  • 2020-12-01 00:41

    I have fixed this and my solution it was only in the Storyboard.

    Changes:

    It added in Identity Inspector -> User Defined Runtime Attributes (these KeyPaths):

    • numberOfLines = 2
    • titleLabel.textAlignment = 1

    User Defined Runtime Attributes

    I added this in attributes inspector:

    • line break = word wrap

    Word wrap

    0 讨论(0)
提交回复
热议问题