Multi-line label on UIButton Swift

I am trying to get a sync button to display Last Sync at (time&date)

. But all I get is one line of abbreviated text.

// Sync Button

syncBtn.frame = CGRectMake(15, height-60, 120, 40)

syncBtn.addTarget(self, action: "syncBtnPressed", forControlEvents: UIControlEvents.TouchUpInside)

syncBtn.setTitle("Last Sync: Never", forState: UIControlState.Normal)

syncBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)

syncBtn.layer.borderColor = UIColor.whiteColor().CGColor

syncBtn.layer.borderWidth = 1

syncBtn.layer.cornerRadius = 5

syncBtn.titleLabel?.font = UIFont(name: "Avenir", size: 10)

syncBtn.alpha = 0.5

syncBtn.titleLabel?.sizeToFit()

syncBtn.titleLabel?.textAlignment = NSTextAlignment.Center

syncBtn.titleLabel?.numberOfLines = 2

self.view.addSubview(syncBtn)

      

This is the function to get and set the date on the label

func printTimestamp(){
    var timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .ShortStyle, timeStyle: .ShortStyle)
    self.syncBtn.titleLabel?.text = ("Last Sync at: " + timestamp)
}

      

Anyone who can fix this problem?

+3


source to share


2 answers


Use SetTitle method instead of .text, when you use .text it sets the title text but the constraints are not updated accordingly, so you need to use the SetTitle method and set adjustsFontSizeToFitWidth to true



self.syncBtn.setTitle(timeStamp, forState: UIControlState.Normal)
self.syncBtn.titleLabel?.adjustsFontSizeToFitWidth = true

      

+2


source


create a UIButton with multiple lines of text

Possible software



  override func viewDidAppear(animated: Bool){
    super.viewDidAppear(animated)
      btnTwoLine.setTitle("Mulitple line", forState:     UIControlState.Normal)
      btnTwoLine.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping;

    }

      

+4


source







All Articles